SpringBoot使用注解方式整合Redis
1.首先导入使用Maven导入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
2.在application.properties配置信息
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=123456
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=200
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=1000ms
3.编写Redis工具类
@Configuration
@ConditionalOnClass(RedisOperations.class) //系统中有RedisOperations类时
@EnableConfigurationProperties(RedisProperties.class) //启动RedisProperties这个类
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Autowired
RedisTemplate redisTemplate;
// 配置缓存管理器
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
LettuceConnectionFactory jedisConnectionFactory = (LettuceConnectionFactory) redisTemplate.getConnectionFactory();
jedisConnectionFactory.setDatabase(2); //指定dbindex
redisTemplate.setConnectionFactory(jedisConnectionFactory);
jedisConnectionFactory.resetConnection(); RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(60*20)) // 20分钟缓存失效
// 设置key的序列化方式
// .entryTtl(Duration.ofSeconds(10))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
// 设置value的序列化方式
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new FastJsonRedisSerializer(Object.class)))
// 不缓存null值
.disableCachingNullValues();
RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
.cacheDefaults(config)
.transactionAware()
.build();
return redisCacheManager;
}
}
package com.FireService.config; import java.nio.charset.Charset; import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature; public class FastJsonRedisSerializer<T> implements RedisSerializer<T> { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private Class<T> clazz;
static {
ParserConfig.getGlobalInstance().addAccept("com.FireService");
}
public FastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
} @Override
public byte[] serialize(T t) throws SerializationException {
if (null == t) {
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
} @Override
public T deserialize(byte[] bytes) throws SerializationException {
if (null == bytes || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return (T) JSON.parseObject(str, clazz);
} }
4.SpringBoot有关缓存的几个注解
@Cacheable:查询
可选属性:
cacheNames/value:指定缓存组件的名字;
key:缓存数据使用的key,可以用来指定。默认即使用方法参数的值
keyGenerator:key的生成器,可以自己指定key的生成器的组件id
//自定义配置类配置keyGenerator
@Configuration
public class MyCacheConfig {
@Bean("myKeyGenerator")
public KeyGenerator keyGenerator(){
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
return method.getName()+"["+ Arrays.asList(params).toString() +"]";
}
};
}
}
cacheManager:指定缓存管理器;或者cacheResolver获取指定解析器
condition:指定符合条件的情况下才缓存;如condition="#id>0"
unless:否定缓存,当unless指定的条件为true,方法的返回值不会被缓存,可以获取到结果进行判断;如unless="#result==null";
sync:是否使用异步模式
例如:
@Cacheable(value = "RedisInfo", key = "#root.methodName+'['+#account+']'")
@ResponseBody
@RequestMapping("/RedisTest")
public Result findUserOrder(String account) throws Exception{
if(account!=null) {
List<Map<String, Object>> list=orderFindGoods.findUserOrder(account);
return Results.successWithData(list, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
}else {
return Results.failure();
}
}
运行项目查看结果
1.第一次访问
查看Druid连接信息
可以看出当前执行sql语句为一次
再一次刷新页面
此时使用RedisDestopManager查看数据
成功!!
@CachePut:更新
既调用方法,又更新缓存数据,可达到同步更新缓存;
修改了数据库的某个数据,同时更新缓存
运行时机:
1、先调用运行方法;
2、将目标方法的结果缓存起来
value:缓存名 key:缓存的key其中#result表示方法返回的结果(确保更新的key和查询一致即可做到同时更新数据库数据和缓存中的数据)
@CachePut(value="user",key = "#result.id")
public User updateUser(User user){
System.out.println("updateUser:"+user);
userMapper.updateUser(user);
return user;
}
@CacheEvict:删除
缓存清除:目的是为了删除一个数据并删掉缓存
key:指定要清除的数据(对应上key可实现目的即同时做到删除数据库和缓存中的数据)
allEntries =true:指定清楚这个缓存中所有的数据
beforeInvocation = false:缓存的清楚是否在方法之前执行,默认代表是在方法之后执行
@CacheEvict(value = "user",key = "#id")
public void deleteUser(Integer id){
System.out.println("deleteUser:"+id);
userMapper.deleteUserById(id);
}
具体代码我就不写了。大家可以自己尝试一下!
SpringBoot使用注解方式整合Redis的更多相关文章
- 实例讲解Springboot以Template方式整合Redis及序列化问题
1 简介 之前讲过如何通过Docker安装Redis,也讲了Springboot以Repository方式整合Redis,建议阅读后再看本文效果更佳: (1) Docker安装Redis并介绍漂亮的可 ...
- 实例讲解Springboot以Repository方式整合Redis
1 简介 Redis是高性能的NoSQL数据库,经常作为缓存流行于各大互联网架构中.本文将介绍如何在Springboot中整合Spring Data Redis,使用Repository的方式操作. ...
- springboot学习笔记-3 整合redis&mongodb
一.整合redis 1.1 建立实体类 @Entity @Table(name="user") public class User implements Serializable ...
- Spring、SpringMVC注解方式整合
1 原理 Web容器在启动的时候,会扫描每个jar包下的META-INF/services/javax.servlet.ServletContainerInitializer文件. 加载META-IN ...
- 【SpringBoot】Springboot2.x整合Redis(一)
备注: springboto整合redis依赖于spring-boot-starter-data-redis这个jar 一,项目环境和依赖 1.POM.xml配置 <parent> < ...
- springboot注解方式使用redis缓存
引入依赖库 在pom中引入依赖库,如下 <dependency> <groupId>org.springframework.boot</groupId> <a ...
- SpringBoot学习- 5、整合Redis
SpringBoot学习足迹 SpringBoot项目中访问Redis主要有两种方式:JedisPool和RedisTemplate,本文使用JedisPool 1.pom.xml添加dependen ...
- 33. Springboot 系列 原生方式引入Redis,非RedisTemplate
0.pom.xml <dependency> <groupId>redis.clients</groupId> <artifactId>jedis&l ...
- SpringBoot(三)整合Redis
spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化. redis介绍 Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结 ...
随机推荐
- mysql sql的分类、运算符、常用的数据类型
SQL (结构化查询语言)的分类 DML(数据操作语言),关键字 insert,update,delete, DCL(数据控制语言),控制权限,grand,revoke 授权,回收 DDL(数据定义语 ...
- arm-linux-readelf 的使用
1. 读 elf 文件开始的文件头部 [arm@localhost gcc]$ armlinuxreadelf h hello ELF Header: Magic: 7f 45 4c 46 ...
- shell 基本系统命令,关机重启,查看版本,查手册,日期,磁盘,历史命令
1. 查看系统版本及内核版本 cat /etc/issue 查看系统版本 uname -r 查看内核版本 2. 关机重启命令 关机: shutdown -h now 立即关机 shut ...
- MySQL数据库之DML(数据操作语言)
对表记录的增删改 1.MySQL之DML创建数据表user create table user( id int unsigned not null auto_increment primary key ...
- windows 10 无法启动 windows update 服务 错误 0x80070005 拒绝访问
windows 10 无法启动 windows update 服务 错误 0x80070005 拒绝访问: 解决方法: 首先重命名系统盘 windows目录下的代号为“SoftwareDistribu ...
- JAVA算法之简单排序
冒泡排序: 在概念上是排序算法中最简单的,但是运行起来非常慢,冒泡排序遵循以下几个规则(假如我们现在要给一队打乱的足球队员排序): 比较两个队员 如果左边的队员比右边的高,则交换位置 向右移动一位,比 ...
- ubuntu下安装git提示无root权限
apt-get install git 获取git指令 sudo passwd root 重置unix密码 su root 键入密码 参考链接 https://www.cnblogs.com/2she ...
- Linux 添加时间
添加在指令后面 `date +%Y%m%d%H%M`注意date和+之间一定要有空格 ps: %% 一个文字的 % %a 当前locale 的星期名缩写(例如: 日,代表星期日) %A ...
- 关于 argc 和 argv
https://stackoverflow.com/questions/3898021/regarding-mainint-argc-char-argv 当使用命令行启动程序,或者给程序传输参数时,可 ...
- RocketMQ源码分析之RocketMQ事务消息实现原下篇(事务提交或回滚)
摘要: 事务消息提交或回滚的实现原理就是根据commitlogOffset找到消息,如果是提交动作,就恢复原消息的主题与队列,再次存入commitlog文件进而转到消息消费队列,供消费者消费,然后将原 ...