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的更多相关文章

  1. 实例讲解Springboot以Template方式整合Redis及序列化问题

    1 简介 之前讲过如何通过Docker安装Redis,也讲了Springboot以Repository方式整合Redis,建议阅读后再看本文效果更佳: (1) Docker安装Redis并介绍漂亮的可 ...

  2. 实例讲解Springboot以Repository方式整合Redis

    1 简介 Redis是高性能的NoSQL数据库,经常作为缓存流行于各大互联网架构中.本文将介绍如何在Springboot中整合Spring Data Redis,使用Repository的方式操作. ...

  3. springboot学习笔记-3 整合redis&mongodb

    一.整合redis 1.1 建立实体类 @Entity @Table(name="user") public class User implements Serializable ...

  4. Spring、SpringMVC注解方式整合

    1 原理 Web容器在启动的时候,会扫描每个jar包下的META-INF/services/javax.servlet.ServletContainerInitializer文件. 加载META-IN ...

  5. 【SpringBoot】Springboot2.x整合Redis(一)

    备注: springboto整合redis依赖于spring-boot-starter-data-redis这个jar 一,项目环境和依赖 1.POM.xml配置 <parent> < ...

  6. springboot注解方式使用redis缓存

    引入依赖库 在pom中引入依赖库,如下 <dependency> <groupId>org.springframework.boot</groupId> <a ...

  7. SpringBoot学习- 5、整合Redis

    SpringBoot学习足迹 SpringBoot项目中访问Redis主要有两种方式:JedisPool和RedisTemplate,本文使用JedisPool 1.pom.xml添加dependen ...

  8. 33. Springboot 系列 原生方式引入Redis,非RedisTemplate

     0.pom.xml <dependency> <groupId>redis.clients</groupId> <artifactId>jedis&l ...

  9. SpringBoot(三)整合Redis

    spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化. redis介绍 Redis是目前业界使用最广泛的内存数据存储.相比memcached,Redis支持更丰富的数据结 ...

随机推荐

  1. pytorch,cuda8,torch.cuda.is_available return flase (ubuntu14)

    因为ubuntu 系统是14.0的,安装pytorch1.0的时候,本身已经安装好了cuda8,在验证gpu的时候,torch.cuda.is_available()返回false 安装命令是: co ...

  2. mysql查询小技巧

    如果所传bookTypeName为空则执行select * from t_bookType(搜索框里未输入信息) 否则追加 and bookTypeName like  '%"+bookTy ...

  3. 2019-8-31-dotnet-判断程序当前使用管理员运行降低权使用普通权限运行

    title author date CreateTime categories dotnet 判断程序当前使用管理员运行降低权使用普通权限运行 lindexi 2019-08-31 16:55:58 ...

  4. leetcode-8-字符串转换整数(atoi)

    题目描述: 方法一:正则 class Solution: def myAtoi(self, str: str) -> int: return max(min(int(*re.findall('^ ...

  5. android GPS: code should explicitly check to see if permission is available

    转载的,感谢作者,由于我找了很久才找到这个解决方法,因此我自己再转一遍 原文链接 https://blog.csdn.net/qinwendou/article/details/77849048 if ...

  6. selenium基础(参数化脚本)

    参数化脚本 什么是参数化 参数化就是用包含多组数据的参数列表,使之替换脚本中的响应常量值,这样,在脚本运行的时候,就会使用参数表中的数据来代替脚本中的常量值 由于参数表中包含了多组数据,所以执行用例时 ...

  7. Minifilter 相关

    FLTFL_OPERATION_REGISTRATION_SKIP_PAGING_IO 商用软件一定要过滤掉这个类型的请求,这个类型的请求响应非常慢. FLTFL_OPERATION_REGISTRA ...

  8. Hibernate的一对一映射

    一.创建Java工程,新建Lib文件夹,加入Hibernate和数据库(如MySql.Oracle.SqlServer等)的Jar包,创建 hibernate.cfg.xml 文件,并配置,配置项如下 ...

  9. go string和[ ]byte

    https://www.cnblogs.com/zhangboyu/p/7623712.html

  10. Leetcode92. Reverse Linked List II反转链表

    反转从位置 m 到 n 的链表.请使用一趟扫描完成反转. 说明: 1 ≤ m ≤ n ≤ 链表长度. 示例: 输入: 1->2->3->4->5->NULL, m = 2 ...