使用Redis缓存资讯的类别列表

首先,使用公共的接口文件定义Redis中的数据的Key值,例如,在tmall-common项目中创建此接口

public interface ContentCacheConsts {

    String KEY_CATEGORY_LIST = "content:category:list";

}

需要在repository层实现读写Redis,则先在项目的根包下创建dao.cache.ICategoryCacheRepository接口,此接口应该继承自以上定义Key值的接口,则此接口的实现类可以直接使用以上Key值,并在接口中声明抽象方法:

public interface ICategoryCacheRepository extends ContentCacheConsts {

    void saveList(List<CategoryListItemVO> categoryList);

    List<CategoryListItemVO> list();

}

在项目的根包下创建dao.cache.impl.CategoryCacheRepositoryImpl类,实现以上接口,并重写接口中定义的抽象方法:

@Repository
public class CategoryCacheRepositoryImpl implements ICategoryCacheRepository {

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    @Override
    public void saveList(List<CategoryListItemVO> categoryList) {
        ListOperations<String, Serializable> opsForList = redisTemplate.opsForList();
        for (CategoryListItemVO category : categoryList) {
            opsForList.rightPush(KEY_CATEGORY_LIST, category);
        }
    }

    @Override
    public List<CategoryListItemVO> list() {
        long start = 0;
        long end = -1;
        ListOperations<String, Serializable> opsForList = redisTemplate.opsForList();
        List range = opsForList.range(KEY_CATEGORY_LIST, start, end);
        return range;
    }

}

 

然后,需要在service层调用读写Redis的repository

@Override
public PageData<CategoryListItemVO> list(Integer pageNum) {
    log.debug("开始处理【查询类别列表】的业务,页码:{}", pageNum);
    // return categoryRepository.list(pageNum, defaultQueryPageSize);
    List<CategoryListItemVO> list = categoryCacheRepository.list();
    PageData<CategoryListItemVO> pageData = new PageData<>();
    pageData.setList(list);
    pageData.setMaxPage(1);
    pageData.setPageSize(list.size());
    pageData.setTotal(list.size() + 0L);
    pageData.setPageNum(1);
    return pageData;
}

经过以上调整后,即可达成新的效果,Controller并不需要做任何调整。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值