当前位置:网站首页>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 {
// 省略其他代码
}
边栏推荐
猜你喜欢
One-arm routing experiment and three-layer switch experiment
Late night drinking, 50 classic SQL questions, really fragrant~
多线程之传递参数
数组&的运算
UI刘海屏适配方式
Tencent Internal Technology: Evolution of Server Architecture of "The Legend of Xuanyuan"
Error correction notes for the book Image Processing, Analysis and Machine Vision
Drools规则引擎快速入门(一)
vs2017关于函数命名方面的注意事项
滚动条问题,未解决
随机推荐
DevOps流程demo(实操记录)
D39_ coordinate transformation
H5开发调试-Fiddler手机抓包
The future of cloud gaming
LeetCode practice and self-comprehension record (1)
【FAQ】What is Canon CCAPI
Take you in-depth understanding of cookies
ev加密视频转换成MP4格式,亲测可用
Nacos集群搭建
The method of using ROS1 bag under ROS2
ALC experiment
Tencent Internal Technology: Evolution of Server Architecture of "The Legend of Xuanyuan"
人人AI(吴恩达系列)
深入分析若依数据权限@datascope (注解+AOP+动态sql拼接) 【循序渐进,附分析过程】
GetEnumerator method and MoveNext and Reset methods in Unity
Shadowless Cloud Desktop
txt文件英语单词词频统计
数组&的运算
cs231n learning record
NACOS Configuration Center Settings Profile