当前位置:网站首页>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 {
// 省略其他代码
}
边栏推荐
- 邮件管理 过滤邮件
- The hook of the operation of the selenium module
- Quick Start to Drools Rule Engine (1)
- el-progress实现进度条颜色不同
- 关于Antd的Affix突然不好用了,或者Window的scroll监听不好用了
- sql server duplicate values are counted after
- Take you in-depth understanding of cookies
- js 使用雪花id生成随机id
- Late night drinking, 50 classic SQL questions, really fragrant~
- The use of three parameters of ref, out, and Params in Unity3D
猜你喜欢

单片机期末复习大题

el-progress implements different colors of the progress bar

NB-IOT智能云家具项目系列实站

Drools规则引擎快速入门(一)

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

NB-IOT智能云家具项目系列实站

Late night drinking, 50 classic SQL questions, really fragrant~

前置++和后置++的区别

The use of three parameters of ref, out, and Params in Unity3D

BIO, NIO, AIO practical study notes (easy to understand theory)
随机推荐
网络协议基础-学习笔记
VSCode编写OpenCV
七种让盒子水平垂直居中的方法
淘宝宝贝页面制作
The cocos interview answers you are looking for are all here!
Vim tutorial: vimtutor
Transformer interprets and predicts instance records in detail
浏览器兼容汇总
UI刘海屏适配方式
LaTeX笔记
What is the website ICP record?
前置++和后置++的区别
D39_ coordinate transformation
Browser Storage WebStorage
Q 2020, the latest senior interview Laya soul, do you know?
Transformer详细解读与预测实例记录
Shadowless Cloud Desktop
The size of the screen adaptation
Mina's long and short connections
格式化代码缩进的小技巧