1. 程式人生 > 實用技巧 >獲取rdis的幾種方式

獲取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:刪除