当前位置:网站首页>Redis的使用
Redis的使用
2022-08-05 05:25:00 【技术的搬运工】
前言
SprintBoot 项目中,用到的 redis 的方式有四种:
- 利用注解
- 利用 RedisTemplate
- 利用 CacheManager
- 利用 Jedis
这里只提供给大家可以使用的几种方式, 关于这四种方式网上的文章很多,这里不再赘述
1、注解方式
主要注解有:
- @Cacheable
- @Caching
- @CacheEvic
这里需要注意一下,@Cacheable 所在的 package 是 spring 的,
有些bug是因为使用了swagger里面的@Cacheable注解导致缓存无效。
import org.springframework.cache.annotation.Cacheable; // 正解的import
import springfox.documentation.annotations.Cacheable; // 错误的import
另外,需要注意同一个类内部调用缓存不生效和不同类调用缓存无法清除等问题,
可以参考以下文章:
SpringCache @Cacheable 在同一个类中调用方法,导致缓存不生效的问题及解决办法
2、RedisTemplate方式
使用这种方式操作redis,需要注意如果缓存的是一个对象,这对象的必须要是可序列化的,即必须要继承Serializable,否则缓存时会报序列化失败。
使用redisTemplate方式的一个好处提供的方法比较多,配置过期时间比较自由,可以发挥redis的诸多功能。
3、CacheManager方式
用由工具类CacheUtils来操作,UserUtils 里面用来 CacheUtils 缓存用户信息。
为了方便使用,我加了一个泛型方法
/**
* 获取缓存,没有则执行表达式,并将结果放入缓存
* @param cacheName
* @param key
* @param supplier
* @param <T>
* @return
*/
public static <T> T get(String cacheName, String key, Supplier<T> supplier) {
Object obj = get(cacheName, key);
if (obj != null) {
return (T) obj;
} else {
T result = supplier.get();
put(cacheName, key, result);
return result;
}
}
4、Jedis方式
Jedis 工具类
package org.linlinjava.litemall.common.utils;
/**
* @title: StringUtils.java
* @package cn.jeeweb.common.util
* @description: Jedis Cache 工具类
*/
public class JedisUtils {
// 省略其他代码
}
边栏推荐
猜你喜欢

【FAQ】CCAPI Compatible EOS Camera List (Updated in August 2022)

Writing OpenCV in VSCode

LaTeX 图片加标题 文本分栏自动换行

DisabledDate date picker datePicker

From "dual card dual standby" to "dual communication", vivo took the lead in promoting the implementation of the DSDA architecture

Take you in-depth understanding of cookies

txt文件英语单词词频统计

多用户商城多商户B2B2C拼团砍价秒杀支持小程序H5+APP全开源

Wireshark packet capture and common filtering methods

Error correction notes for the book Image Processing, Analysis and Machine Vision
随机推荐
Collection of error records (write down when you encounter them)
docker部署完mysql无法连接
GetEnumerator method and MoveNext and Reset methods in Unity
淘宝宝贝页面制作
【FAQ】CCAPI兼容EOS相机列表(2022年8月 更新)
Transformer interprets and predicts instance records in detail
单片机期末复习大题
亚马逊美国站:马术头盔CPC认证标准要求
盒子模型中过度约束问题及其解决办法
记录vue-页面缓存问题
Network Troubleshooting Basics - Study Notes
花花省V5淘宝客APP源码无加密社交电商自营商城系统带抖音接口
input detailed file upload
DevOps process demo (practical record)
淘宝客APP带自营商城本地生活CPS外卖优惠电影票话费更新渠道跟单生活特权V3
H5 的浏览器存储
UI刘海屏适配方式
One-arm routing experiment and three-layer switch experiment
NACOS Configuration Center Settings Profile
selenium learning