当前位置:网站首页>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 {
// 省略其他代码
}
边栏推荐
- Some basic method records of commonly used languages in LeetCode
- document.querySelector()方法
- LaTeX uses frame to make PPT pictures without labels
- LeetCode practice and self-comprehension record (1)
- 淘宝宝贝页面制作
- 指针常量与常量指针 巧记
- The hook of the operation of the selenium module
- ## 简讲protobuf-从原理到使用
- D46_Force applied to rigid body
- Email management Filter emails
猜你喜欢

BIO, NIO, AIO practical study notes (easy to understand theory)

Alibaba Cloud Video on Demand

Nacos集群搭建

Successful indie developers deal with failure & imposters

DevOps process demo (practical record)

单片机期末复习大题

cs231n学习记录

Vim tutorial: vimtutor

Mina disconnects and reconnects

LeetCode practice and self-comprehension record (1)
随机推荐
Shadowless Cloud Desktop
VS Code私有服务器部署(私有化)
txt文件英语单词词频统计
The 25 best free games on mobile in 2020
sql server duplicate values are counted after
lingo入门——河北省第三届研究生建模竞赛B题
The method of using ROS1 bag under ROS2
浏览器兼容汇总
The use of three parameters of ref, out, and Params in Unity3D
LaTeX笔记
cs231n学习记录
Does flink cdc currently support Gauss database sources?
LeetCode刷题记录(2)
亚马逊美国站:马术头盔CPC认证标准要求
Network Protocol Fundamentals - Study Notes
邮件管理 过滤邮件
D39_Eulerian Angles and Quaternions
Chengyun Technology was invited to attend the 2022 Alibaba Cloud Partner Conference and won the "Gathering Strength and Going Far" Award
vscode笔记
NAT experiment