• 获取rdis的几种方式


    第一种

    import org.springframework.data.redis.core.StringRedisTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;
    一丶获取验证码 ValueOperations
    <String, String> opsForValue = redisTemplate.opsForValue(); String code = opsForValue.get(keyCode); if(null==code){ return new ResultObj(-1,"验证码过期"); } 二存设置有效期 ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(100, 38, 4, 4); String code = captcha.getCode(); ValueOperations<String, String> opsForValue = redisTemplate.opsForValue(); opsForValue.set(codeKey,code); opsForValue.getOperations().expire(codeKey,60, TimeUnit.SECONDS);


    另一种写法

    @Autowired
      private StringRedisTemplate redis;

       private static final String AUTH_CODE_PREFIX = "AUTH:CODE:"; // UUID

    private void checkAuthCode(String sessionUUID, String imageCode) {
        if(StringUtils.hasText(sessionUUID)&&StringUtils.hasText(imageCode)) {
            String authCode = redis.opsForValue().get(AUTH_CODE_PREFIX+sessionUUID);
                 if(!imageCode.equalsIgnoreCase(authCode)) {
               throw new AuthenticationException("验证码错误");
              }

       }else {
            throw new RuntimeException("验证码或uuid为null");
    }

    }

    @GetMapping("captcha.jpg")
    public void captcha(@RequestParam(required = true)String uuid,HttpServletResponse resp){
           log.info("获取验证码,uuid为{}",uuid);
               // 使用Hutool 来生成验证码
              LineCaptcha createLineCaptcha = CaptchaUtil.createLineCaptcha(150, 45, 4, 4);
               String code = createLineCaptcha.getCode();
          // 将验证码存储在redis里面,并且设置过期时间
               redis.opsForValue().set(AUTH_CODE_PREFIX+uuid, code,60,TimeUnit.SECONDS);
          log.info("验证码为{}",code);
    try {
             resp.getOutputStream().write(createLineCaptcha.getImageBytes());
         } catch (IOException e) {
         e.printStackTrace();
      }
    }




    第二种缓存

    
    

    import org.springframework.cache.annotation.CacheEvict;
    import org.springframework.cache.annotation.CachePut;
    import org.springframework.cache.annotation.Cacheable;

      @Override
        @CachePut(cacheNames = "com.sxt.system.service.impl.DeptServiceImpl",key = "#result.id")
        public Dept saveDept(Dept dept) {
            this.deptMapper.insert(dept);
            return dept;
        }
    
    
        @CachePut(cacheNames = "com.sxt.system.service.impl.DeptServiceImpl",key = "#result.id")
        @Override
        public Dept updateDept(Dept dept) {
            Dept selectById = this.deptMapper.selectById(dept.getId());
            BeanUtil.copyProperties(dept,selectById, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            this.deptMapper.updateById(selectById);
            return selectById;
        }
    
    
    
        @Cacheable(cacheNames = "com.sxt.system.service.impl.DeptServiceImpl",key = "#id")
        @Override
        public Dept getById(Serializable id) {
            return super.getById(id);
        }
    
    
        @CacheEvict(cacheNames = "com.sxt.system.service.impl.DeptServiceImpl",key = "#id")
        @Override
        public boolean removeById(Serializable id) {
            return super.removeById(id);
        }
     @CachePut(cacheNames = "com.sxt.business.service.impl.GoodsServiceImpl",key = "#result.id")
        @Override
        public Goods saveGoods(Goods goods) {
            this.goodsMapper.insert(goods);
            return goods;
        }
    
        @CachePut(cacheNames = "com.sxt.business.service.impl.GoodsServiceImpl",key = "#result.id")
        @Override
        public Goods updateGoods(Goods goods) {
    
            Goods selectById = this.goodsMapper.selectById(goods.getId());
            BeanUtil.copyProperties(goods,selectById, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            this.goodsMapper.updateById(selectById);
            return selectById;
        }
    
        @Override
        public DataGridView getAllAvailableGoods() {
            QueryWrapper<Goods> qw=new QueryWrapper<>();
            qw.eq("available", Constant.AVAILABLE_TRUE);
            List<Goods> goods = this.goodsMapper.selectList(qw);
            return new DataGridView(goods);
        }
    
        @Override
        public DataGridView getGoodsByProviderId(Integer providerid) {
            if(null==providerid){
                return new DataGridView();
            }
            QueryWrapper<Goods> qw=new QueryWrapper<>();
            qw.eq("available", Constant.AVAILABLE_TRUE);
            qw.eq("providerid",providerid);
            List<Goods> goods = this.goodsMapper.selectList(qw);
            return new DataGridView(goods);
        }
    
        @Cacheable(cacheNames = "com.sxt.business.service.impl.GoodsServiceImpl",key = "#id")
        @Override
        public Goods getById(Serializable id) {
            return super.getById(id);
        }
    
        @CacheEvict(cacheNames = "com.sxt.business.service.impl.GoodsServiceImpl",key = "#id")
        @Override
        public boolean removeById(Serializable id) {
            return super.removeById(id);
        }

    缓存数据字典

      import org.springframework.data.redis.core.StringRedisTemplate;
    
      @Autowired
        private StringRedisTemplate redisTemplate;
    
     @Override
        public void dictCacheAsync() {
            //查询出所有可用的字典类型数据
            QueryWrapper<DictType> qw=new QueryWrapper<>();
            qw.eq(DictType.COL_STATUS,Constants.STATUS_TRUE);
            List<DictType> dictTypes = this.dictTypeMapper.selectList(qw);
            for (DictType dictType : dictTypes) {
                QueryWrapper<DictData> qdw=new QueryWrapper<>();
                qdw.eq(DictData.COL_STATUS,Constants.STATUS_TRUE);
                qdw.eq(DictData.COL_DICT_TYPE,dictType.getDictType());
                qdw.orderByAsc(DictData.COL_DICT_SORT);
                List<DictData> dictDataList = dictDataMapper.selectList(qdw);
                //转成json串
                String json= JSON.toJSONString(dictDataList);
                ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
                opsForValue.set(Constants.DICT_REDIS_PROFIX+dictType.getDictType(),json);
            }
        }

    总结

    缓存问题
    @Cacheable:对请求参数和结果缓存,下次用同一个参数请求,就不再调用方法,直接从缓存中拿出数据
    
    @CacheEvict:清空缓存
    
    @CachePut:更新缓存,保证方法一定会被调用,同时更新缓存中的对应的数据。
    
    @EnableCaching:开启缓存的注解,开启了才可以使用缓存
    
    
    关于注解
    
    @EnableCaching 在启动类上加上注解启动缓存
    #作用在你要缓存的数据上
    @Cacheable(key="#id",cacheNames="com.sxt.service.impl.MenuServiceImpl")      查询
    @Cacheput 添加
    @CacheEvict:删除
  • 相关阅读:
    Mongodb在window上启动
    java:JQuery(Ajax,JSON)
    SqlServer:SqlServer(sql,游标,定时作业,行转列,列转行,公用表达式递归,merge合并)
    java:WebService
    java:svn
    java:Echarts,POI
    java:LeakFilling(Other)
    java:activiti(工作流简介 )
    Linux:lvm磁盘分区,动态扩容
    java:dubbo
  • 原文地址:https://www.cnblogs.com/javakangkang/p/14023987.html
Copyright © 2020-2023  润新知