Redis实战场景(笔记)

Reids

Redis手机验证码(1)

  @RequestMapping("/getloginsms")
    @ResponseBody
    public DemoEntity getSmsCode(@RequestParam(value = "userId") String userId) {
        Jedis jedis = RedisProvider.getJedis();
        DemoEntity entity = new DemoEntity();
        String str= null;
 
        //1. 判断是否缓存该账号验证码
        boolean isExist = jedis.exists(userId+ "_smslogin");
        if (isExist) {
            str= jedis.get(userId+ "_smslogin");   //从redis取出验证码
 
            //设置返回对象的参数
            return  entity;
        } else {
            //没找到该账号的验证码,新生成验证码
            str= TestRedis.getRandom();
 
            jedis.setex(userId+ "_smslogin", 60, str);   //缓存验证码并设置超时时间(setex表示如果 key 已经存在, SETEX 命令将会替换旧的值)
        }
 
 
        //设置返回值参数
        entity.setPwd(str);
 
        return entity;
    }
    //获取6位随机数作为验证码
    public static String getRandom() {
        String num = "";
        for (int i = 0 ; i < 6 ; i ++) {
            num = num + String.valueOf((int) Math.floor(Math.random() * 9 + 1));
        }
        return num;
    }

Redis手机验证码(2)三次限制

/**
 * 需求:
 * 1.将6位数字的验证码,存储在redis中
 * 2.一天内只允许获取三次密码,每次密码有效时间为2分钟
 */
public class TestValidateCode {

    public static void main(String[] args) {
        //System.out.println("验证码 = "+getCode());

        //设置验证码
        //setValidateCode("13912127777");

        //登陆
        login("13912127777","778380");
    }

    /**
     * 1.生成6位随机数字的验证码
     */
    public static String getCode(){
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            int n = random.nextInt(10);
            code+=n;
        }
        return code;
    }

    /**
     * 2.将验证码存储在redis中,只允许发生3次,且验证码有效期是2分钟
     */
    public static void setValidateCode(String phone){
        Jedis jedis = new Jedis("139.224.102.249",6379);

        String codeKey = "validate_"+phone+"_code";   //validate_13911113333_code
        String countKey = "validate_"+phone+"_count"; //validate_13911113333_count

        String count = jedis.get(countKey);
        if(count==null){
            //第一次获取验证码  setex设置过期时间,计数器一天内有效
            jedis.setex(countKey,24*60*60,"1");
        }else if(Integer.parseInt(count)<=2){
            //计数器+1
            jedis.incr(countKey);
        }else if(Integer.parseInt(count)>2){
            System.out.println("今天内已经获取三次密码,请明日再来!");
            jedis.close();
            return;
        }

        //设置验证码,每次密码有效时间为2分钟
        jedis.set(codeKey,getCode());
        jedis.expire(codeKey,120);  //单位秒 s
        jedis.close();
    }

    /**
     * 3.登陆,通过验证码进行登陆
     */
    public static void login(String phone,String code){
        Jedis jedis = new Jedis("139.224.102.249",6379);

        String redisCode = jedis.get("validate_"+phone+"_code");
        if(redisCode==null){
            System.out.println("验证码已失效,请重新获取");
            return;
        }

        if(redisCode.equals(code)){
            System.out.println("登陆成功");
        }else{
            System.out.println("登陆失败");
        }
        jedis.close();
    }
}

购物车(未登录和已登录)

实体层

未登录购物车实体类

@Data
public class CookieCart {
     //商品id
    private Long productId;
    //商品数量
    private int amount;

}

登录用户购物车实体类

@Data
public class Cart {

    private Long userId;
    //商品id
    private Long productId;
    //商品数量
    private int amount;

}

业务层

    /**
     * 未登录
     * 添加购物车
     */
    @PostMapping(value = "/addCart")
    public void addCart(CookieCart obj) {
        //获取一个Cookies的cardId
        String cartId=this.getCookiesCartId();
        String key=COOKIE_KEY+cartId;
        Boolean hasKey = redisTemplate.opsForHash().getOperations().hasKey(key);
        //存在
        if(hasKey){
            //保存key为购物车,hash的key为商品id,value为数量
            this.redisTemplate.opsForHash().put(key, obj.getProductId().toString(),obj.getAmount());
        }else{
            this.redisTemplate.opsForHash().put(key, obj.getProductId().toString(), obj.getAmount());
            this.redisTemplate.expire(key,90, TimeUnit.DAYS);
        }
    }
    
     /**
     * 未登录
     * 更改购物车商品数量
     */
    @PostMapping(value = "/updateCart")
    public void updateCart(CookieCart obj) {
        String cartId=this.getCookiesCartId();
        String key=COOKIE_KEY+cartId;
        this.redisTemplate.opsForHash().put(key, obj.getProductId().toString(),obj.getAmount());
    }
    /**
     * 未登录
     * 删除购物车商品
     */
    @PostMapping(value = "/delCart")
    public void delCart(Long productId) {
        String cartId=this.getCookiesCartId();
        String key=COOKIE_KEY+cartId;
        this.redisTemplate.opsForHash().delete(key, productId.toString());
    }
    /**
     * 未登录
     * 查询某个用户的购物车
     */
    @PostMapping(value = "/findAll")
    public CartPage findAll() {
        String cartId=this.getCookiesCartId();
        String key=COOKIE_KEY+cartId;

        CartPage<CookieCart> cartPage=new CartPage();
        //查询该用户购物车的总数
        long size=this.redisTemplate.opsForHash().size(key);
        cartPage.setCount((int)size);

        //查询购物车的所有商品
        Map<String,Integer> map= this.redisTemplate.opsForHash().entries(key);
        List<CookieCart> cartList=new ArrayList<>();
        for (Map.Entry<String,Integer> entry:map.entrySet()){
            CookieCart cart=new CookieCart();
            cart.setProductId(Long.parseLong(entry.getKey()));
            cart.setAmount(entry.getValue());
            cartList.add(cart);
        }
        cartPage.setCartList(cartList);
        return cartPage;
    }

    /**
     * 登录
     * 合并购物车
     * 把cookie中的购物车合并到登录用户的购物车
     */
    @PostMapping(value = "/mergeCart")
    public void mergeCart(Long userId) {
        //第一步:提取未登录用户的cookie的购物车数据
        String cartId=this.getCookiesCartId();
        String keycookie=COOKIE_KEY+cartId;
        Map<String,Integer> map= this.redisTemplate.opsForHash().entries(keycookie);

        //第二步:把cookie中得购物车合并到登录用户的购物车
        String keyuser = "cart:user:" + userId;
        this.redisTemplate.opsForHash().putAll(keyuser,map);

        //第三步:删除redis未登录的用户cookies的购物车数据
        this.redisTemplate.delete(keycookie);

        //第四步:删除未登录用户cookies的cartid
        Cookie cookie=new Cookie("cartId",null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
    
    
    /**
     * 获取cookies
     */
    public  String getCookiesCartId(){
        //第一步:先检查cookies是否有cartid
        Cookie[] cookies =  request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals("cartId")){
                    return cookie.getValue();
                }
            }
        }
        //第二步:cookies没有cartid,直接生成全局id,并设置到cookie里面
        //生成全局唯一id
        long id=this.idGenerator.incrementId();
        //设置到cookies
        Cookie cookie=new Cookie("cartId",String.valueOf(id));
        response.addCookie(cookie);
        return id+"";
    }
}

@Service
public class IdGenerator {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String ID_KEY = "id:generator:cart";

    /**
     * 生成全局唯一id
     */
    public Long incrementId() {
        long n=this.stringRedisTemplate.opsForValue().increment(ID_KEY);
        return n;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值