• maven项目配置redis,实现购物车功能


    1,首先在maven,项目中pom.xml 加入jar包,

    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.9.0</version>
    </dependency>
    2,导入配置文件,applicationContext-jedis.xml,我的在resources 下

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
       <!-- 连接池配置 -->
       <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
          <!-- 最大连接数 -->
          <property name="maxTotal" value="30" />
          <!-- 最大空闲连接数 -->
          <property name="maxIdle" value="10" />
          <!-- 每次释放连接的最大数目 -->
          <property name="numTestsPerEvictionRun" value="1024" />
          <!-- 释放连接的扫描间隔(毫秒) -->
          <property name="timeBetweenEvictionRunsMillis" value="30000" />
          <!-- 连接最小空闲时间 -->
          <property name="minEvictableIdleTimeMillis" value="1800000" />
          <!-- 连接空闲多久后释放, 当空闲时间>该值 且 空闲连接>最大空闲连接数 时直接释放 -->
          <property name="softMinEvictableIdleTimeMillis" value="10000" />
          <!-- 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1 -->
          <property name="maxWaitMillis" value="1500" />
          <!-- 在获取连接的时候检查有效性, 默认false -->
          <property name="testOnBorrow" value="true" />
          <!-- 在空闲时检查有效性, 默认false -->
          <property name="testWhileIdle" value="true" />
          <!-- 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true -->
          <property name="blockWhenExhausted" value="false" />
       </bean>    
       <!-- jedis客户端单机版 -->
       <bean id="jedisPool" class="redis.clients.jedis.JedisPool">
       
          <constructor-arg name="host" value="127.0.0.1"></constructor-arg>
          <constructor-arg name="port" value="6379"></constructor-arg>
          <constructor-arg name="poolConfig" ref="jedisPoolConfig"></constructor-arg>
           <constructor-arg name="timeout" value="2000"></constructor-arg>
           <constructor-arg name="password" value="*****"></constructor-arg> 
       </bean>
    
    
    <bean id="jedisClient" class="com.mmall.dao.jedis.impl.JedisClientSingle"/>
     //jedisclientsingle,文件放到dao层下面,项目可以扫描到的包下面,这个是实现impl
       
       <!-- jedis集群版配置 -->
       <!-- <bean id="redisClient" class="redis.clients.jedis.JedisCluster">
          <constructor-arg name="nodes">
             <set>
                <bean class="redis.clients.jedis.HostAndPort">
                   <constructor-arg name="host" value=""></constructor-arg>
                   <constructor-arg name="port" value="7001"></constructor-arg>
                </bean>
                <bean class="redis.clients.jedis.HostAndPort">
                   <constructor-arg name="host" value=""></constructor-arg>
                   <constructor-arg name="port" value="7002"></constructor-arg>
                </bean>
                <bean class="redis.clients.jedis.HostAndPort">
                   <constructor-arg name="host" value=""></constructor-arg>
                   <constructor-arg name="port" value="7003"></constructor-arg>
                </bean>
                <bean class="redis.clients.jedis.HostAndPort">
                   <constructor-arg name="host" value=""></constructor-arg>
                   <constructor-arg name="port" value="7004"></constructor-arg>
                </bean>
                <bean class="redis.clients.jedis.HostAndPort">
                   <constructor-arg name="host" value=""></constructor-arg>
                   <constructor-arg name="port" value="7005"></constructor-arg>
                </bean>
                <bean class="redis.clients.jedis.HostAndPort">
                   <constructor-arg name="host" value=""></constructor-arg>
                   <constructor-arg name="port" value="7006"></constructor-arg>
                </bean>
             </set>
          </constructor-arg>
          <constructor-arg name="poolConfig" ref="jedisPoolConfig"></constructor-arg>
       </bean>
       <bean id="jedisClientCluster" class="com.ckip.fxsq.rest.dao.impl.JedisClientCluster"></bean> -->
    </beans>
    3,项目下的applicationContext.xml,里面要加上

    <!-- 导入jedis的配置文件 -->
    <import resource="applicationContext-jedis.xml"/>
    4,引入这几个类,调用jedis


    5,这个实现类impl ,里面主要内容,


    6,看下业务流程吧,具体是怎么调用的,先写下服务端的业务

    controller --->service----->serviceImpl

    package com.mmall.controller.app;
    
    /**
     * 购物车
     * lbx
     */
    
    import com.mmall.common.ServerResponse;
    import com.mmall.service.app.ICartService;
    import com.mmall.vo.app.AppCartProductInfoVo;
    import com.mmall.vo.app.AppCartVo;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.*;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    @Controller
    @RequestMapping("app/cart")
    public class AppCartController {
    
        @Autowired
        private ICartService iCartService;
    
    
        /**
         * <p>Title: getRedisCartList</p>
         * <p>Description: 获取Redis中的购物车信息</p>
         */
    //购物车商品列表
        @RequestMapping(value = "getRedisCartList/{userAccount}.do")
        @ResponseBody
        public ServerResponse<AppCartVo> getRedisCartList(@PathVariable String userAccount) {
            try {
                ServerResponse<AppCartVo> cartList = iCartService.getRedisCartList(userAccount);
                return cartList;
            } catch (Exception e) {
                e.printStackTrace();
                return ServerResponse.createByErrorMessage("获取失败");
            }
        }
    
        /**
         * <p>Title: setAppCartVo</p>
         * <p>Description: 将setAppCartVo加入到Redis</p>
         */
    
        @RequestMapping(value = "setCartToReids/{userAccount}.do")
        @ResponseBody
        public ServerResponse<AppCartVo> setCartToReids(@RequestBody AppCartVo appCartVo ,@PathVariable String userAccount,HttpServletRequest request, HttpServletResponse response) {
            try {
                System.out.println("userAccount-------->" + userAccount);
                ServerResponse<AppCartVo> appCartVos = iCartService.setCartToRedis(userAccount, appCartVo);
                return appCartVos;
            } catch (Exception e) {
                e.printStackTrace();
                return ServerResponse.createByErrorMessage("添加失败");
            }
        }
        /**
         * 删除单个商品
         */
        @RequestMapping(value = "deleteCartRedis/{productId}/{userAccount}.do", method = {RequestMethod.POST, RequestMethod.GET})
        @ResponseBody
        public ServerResponse deleteCartRedis(@PathVariable String productId, @PathVariable String userAccount) {
            try {
                ServerResponse isdel = iCartService.deleteCartReids(productId, userAccount);
            } catch (Exception e) {
                e.printStackTrace();
                return ServerResponse.createByErrorMessage("删除失败");
            }
            return ServerResponse.createBySuccessMessage("删除成功");
        }
        /**
         * <p>Title: delSelectRedis</p>
         * 删除选中商品
         */
        @RequestMapping(value = "delSelectRedis/{userAccount}.do")
        @ResponseBody
        public ServerResponse delSelectRedis(@RequestBody AppCartVo appCartVo ,@PathVariable String userAccount,HttpServletRequest request, HttpServletResponse response) {
            try {
                    if(appCartVo.getAppCartProductInfoVos().size()>0){
                        for(AppCartProductInfoVo cartProductInfoVo : appCartVo.getAppCartProductInfoVos()){
                             iCartService.deleteCartReids(cartProductInfoVo.getProductId(), userAccount);
                        }
                    }
                return ServerResponse.createBySuccessMessage("删除成功");
            } catch (Exception e) {
                e.printStackTrace();
                return ServerResponse.createByErrorMessage("添加失败");
            }
        }
    }
    
    

    package com.mmall.service.app;
    
    import com.mmall.common.ServerResponse;
    import com.mmall.vo.app.AppCartVo;
    
    /**
     * @author lbx
     */
    
    public interface ICartService {
    
        //将setAppCartVo加入到Redis
        ServerResponse<AppCartVo> setCartToRedis(String userAccount, AppCartVo appCartVo) throws Exception;
    
        //删除单个商品
        ServerResponse deleteCartReids(String productId, String userAccount) throws Exception;
    
        /*获取Redis中的购物车信息*/
    
        ServerResponse<AppCartVo> getRedisCartList(String userAccount) throws Exception;
    }
    
    
    package com.mmall.service.impl.app;
    
    import com.mmall.common.ServerResponse;
    import com.mmall.controller.app.AppCartController;
    import com.mmall.service.app.ICartService;
    import com.mmall.dao.jedis.JedisClient;
    import com.mmall.util.JsonUtils;
    import com.mmall.vo.app.AppCartProductInfoVo;
    import com.mmall.vo.app.AppCartVo;
    import org.apache.commons.lang3.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service("ICartService")
    public class CartServiceImpl implements ICartService{
    
        private  Logger Logger = LoggerFactory.getLogger(AppCartController.class);
        @Autowired
        private JedisClient jedisClient;
    
    /**
         * <p>Title: getRedisCartList</p>
         * <p>Description: 获取Redis中购物车信息</p>
         */
    
        @Override
        public ServerResponse<AppCartVo> getRedisCartList(String userAccount) {
            try {
                //从缓存中取该用户的购物车商品列表
                String json = jedisClient.get("REDIS_SHOPPINGCART_KEY" + ":" + userAccount + "");
                //判断是否有值
                if (!StringUtils.isBlank(json)) {
                    //把json转换成java对象
                    AppCartVo appCartVo= JsonUtils.jsonToPojo(json, AppCartVo.class);
                    return ServerResponse.createBySuccess(appCartVo);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ServerResponse.createBySuccess(null);
        }
    
    /**
         * <p>Title: setCartToRedis</p>
         * <p>Description: 用户登录状态向购物车Redis中添加商品信息</p>
         */
    
        @Override
        public ServerResponse<AppCartVo> setCartToRedis(String userAccount, AppCartVo appCartVo) {
            try {
                //添加缓存逻辑
                //从缓存中取购userAccount对应的信息
                String json = jedisClient.get("REDIS_SHOPPINGCART_KEY" + ":"+ userAccount);
                Logger.debug("json--->"+json);
                Logger.debug("json--->"+StringUtils.isNotBlank(json));
    
                //判断是否有值
                if (StringUtils.isNotBlank(json)&&!json.equals("null")) {
                    int flagA = 0;
                    //把json转换成java对象
                    //List<AppCartVo> AppCartVolist = JsonUtils.jsonToList(json, AppCartVo.class);
                    AppCartVo cart = JsonUtils.jsonToPojo(json, AppCartVo.class);
    
                    //for(FxsqSkupojo cartRedis : cart.getCartProList()){
                    //Redis中的dealerAccount
                    //String dealerAccountRedis = cartRedis.getCartDealer().getDealerAccount();
                    //传进来AppCartVo中的dealerAccount
                    //String dealerAccountInput = AppCartVo.getCartDealer().getDealerAccount();
                    //获取Redis中的SkuPojolist
                    //List<FxsqSkupojo> SkupojoList = cartRedis.getCartDealer().getSkuPojoList();
                    List<AppCartProductInfoVo> cartProductInfoVos = cart.getAppCartProductInfoVos();
    
                    //如果供应商一样 商品不一样的时候
                    //if(dealerAccountRedis.equals(dealerAccountInput)){
    
                    int flagB = 0;
                    for(AppCartProductInfoVo cartProductInfoVo : cartProductInfoVos){
                        //获取Redis中的ProductId和数量
                        String productId = cartProductInfoVo.getProductId();
                        Long Count = cartProductInfoVo.getQuantityNumber();
                        //获取传过来AppCartVo中的ProductId和数量
                        String productId1 =  appCartVo.getAppCartProductInfoVos().get(0).getProductId();
                        Long Countt1 =  appCartVo.getAppCartProductInfoVos().get(0).getQuantityNumber();
                        //如果商品一样的时候
                        if(productId1.equals(productId)){
                            flagB = 1;
                            //flagA = 1;
                            Long count = Count + Countt1;
                            cartProductInfoVo.setQuantityNumber(count);
                            break;
                        }
                    }
                    //如果商品不一样的时候
                    if(flagB<1){
                       // flagA = 1;
                        //获取传过来AppCartvo中的appCartProductInfoVos
                        AppCartProductInfoVo appCartProductInfoVo = appCartVo.getAppCartProductInfoVos().get(0);
                        //把skuInput塞入到Redis中的SkuList
                        //cartRedis.getCartDealer().getSkuPojoList().add(skuInput);
                        cart.getAppCartProductInfoVos().add(appCartProductInfoVo);
    
                    }
                    //}
                    //}
                    //商家不一样
    
    /*if(flagA<1){
                   cartPojolist.add(cartPojo);
                }*/
    
                    jedisClient.set("REDIS_SHOPPINGCART_KEY" + ":" + userAccount, JsonUtils.objectToJson(cart));
                    jedisClient.expire("REDIS_SHOPPINGCART_KEY" + ":" + userAccount, 86400);
                    return ServerResponse.createBySuccess(cart);
                }else{
                    //List<CartPojo> cartPojolist = new ArrayList<CartPojo>();
                    //cartPojolist.add(cartPojo);
                    //jedisClient.set("REDIS_SHOPPINGCART_KEY" + ":" + userAccount, JsonUtils.objectToJson(cartPojolist));
    
                    jedisClient.set("REDIS_SHOPPINGCART_KEY" + ":" + userAccount, JsonUtils.objectToJson(appCartVo));
                    jedisClient.expire("REDIS_SHOPPINGCART_KEY" + ":" + userAccount, 86400);
                    return ServerResponse.createBySuccess(appCartVo);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return ServerResponse.createByErrorMessage("添加失败");
            }
           // return ServerResponse.createBySuccessMessage("添加成功");
        }
    
    /**
         * 删除单个商品
         */
    
        @Override
        public ServerResponse deleteCartReids(String productId,String userAccount) {
            try {
                String json = jedisClient.get("REDIS_SHOPPINGCART_KEY" + ":"+ userAccount);
                if (!StringUtils.isBlank(json)) {
                    //把json转换成java对象
                    AppCartVo cartRedis = JsonUtils.jsonToPojo(json, AppCartVo.class);
                    List<AppCartProductInfoVo> cartProductInfoVos =  cartRedis.getAppCartProductInfoVos();
                    for(AppCartProductInfoVo cartProductInfoVo : cartProductInfoVos){
                        //判断供应商下的商品数量 如果只有一个商品 删除AppCartVo 如果存在多个 删除cartProductInfoVo
                        if(cartProductInfoVo.getProductId().equals(productId)){
                            //一个供应商下有一个商品
                            if(cartProductInfoVos.size() == 1){
                                cartRedis=null;
                            }else{
                                //一个供应商下多个商品
                                cartProductInfoVos.remove(cartProductInfoVo);
                            }
                            jedisClient.set("REDIS_SHOPPINGCART_KEY" + ":" + userAccount, JsonUtils.objectToJson(cartRedis));
                            jedisClient.expire("REDIS_SHOPPINGCART_KEY" + ":" + userAccount, 86400);
                        }
                    }
                    return ServerResponse.createBySuccessMessage("删除成功");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ServerResponse.createBySuccessMessage("删除成功");
        }
    
    }
    
    

    7,redis 客户端数据存储


    8,看下前台我的页面,前端用的是vue框架,axios,发出的请求


    cartView: function () {
        var _this = this;
        this.apiBaseUrl = getApiBaseUrl();
        axios.get(this.apiBaseUrl+"/app/cart/getRedisCartList/TW0001.do").then(function (response) {
            _this.appCartProductInfoVos = response.data.data.appCartProductInfoVos;
            _this.totalMoney = response.data.data.totalMoney;//要用_this.appCartProductInfoVos,赋值
        }).catch(function (error) {
            console.log(error);
        });
      /* this.$http.get("http://localhost:8080/yqtw_mall/data/cart0.json").then(res=>{
            this.appCartVo = res.body;
           //console.log("--ee-->"+JSON.stringify(this.appCartVo));
        })*/
    },


  • 相关阅读:
    安全测试WEB安全渗透测试基础知识(三)
    二次开发的Selenium Demo版本
    服务端性能测试工具校验v1.2
    渗透H5棋牌游戏棋牌游戏开发
    安全测试WEB安全渗透测试基础知识(一)
    源码网址
    使用ScribeFire写网易博客 imsho@126的日志 网易博客
    ScribeFire:和firefox完美结合的博客离线编辑器 博客联盟
    如何设置让 Everything 在 Win7 下开机启动 小众软件
    流言终结者——C语言内存管理 michael的个人空间 开源中国社区
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13300672.html
Copyright © 2020-2023  润新知