在 Spring Boot 中,默认集成的 Redis 就是 Spring Data Redis,默认底层的连接池使用了 lettuce ,开发者可以自行修改为自己的熟悉的,例如 Jedis。

Spring Data Redis 针对 Redis 提供了非常方便的操作模板 RedisTemplate 。

1、Spring Data Redis

1.1 引入依赖

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>

引入了 Spring Data Redis + 连接池。

1.2 配置 Redis 信息

接下来配置 Redis 的信息,信息包含两方面,一方面是 Redis 的基本信息,另一方面则是连接池信息:

spring.redis.database=0
spring.redis.password=123
spring.redis.port=6379
spring.redis.host=192.168.66.128
spring.redis.lettuce.pool.min-idle=5
spring.redis.lettuce.pool.max-idle=10
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=1ms
spring.redis.lettuce.shutdown-timeout=100ms

自动配置

当开发者在项目中引入了 Spring Data Redis ,并且配置了 Redis 的基本信息,此时,自动化配置就会生效。

我们从 Spring Boot 中 Redis 的自动化配置类中就可以看出端倪:

@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean
public StringRedisTemplate stringRedisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}

这个自动化配置类很好理解:

首先标记这个是一个配置类,同时该配置在 RedisOperations 存在的情况下才会生效(即项目中引入了 Spring Data Redis)

然后导入在 application.properties 中配置的属性

然后再导入连接池信息(如果存在的话)

最后,提供了两个 Bean ,RedisTemplate 和 StringRedisTemplate ,其中 StringRedisTemplate 是 RedisTemplate 的子类,两个的方法基本一致,不同之处主要体现在操作的数据类型不同,RedisTemplate 中的两个泛型都是 Object ,意味者存储的 key 和 value 都可以是一个对象,而 StringRedisTemplate 的 两个泛型都是 String ,意味者 StringRedisTemplate 的 key 和 value 都只能是字符串。如果开发者没有提供相关的 Bean ,这两个配置就会生效,否则不会生效。

1.3 使用

接下来,可以直接在 Service 中注入 StringRedisTemplate 或者 RedisTemplate 来使用:

@Service
public class HelloService {
@Autowired
RedisTemplate redisTemplate;
public void hello() {
ValueOperations ops = redisTemplate.opsForValue();
ops.set("k1", "v1");
Object k1 = ops.get("k1");
System.out.println(k1);
}
}

Redis 中的数据操作,大体上来说,可以分为两种:

针对 key 的操作,相关的方法就在 RedisTemplate 中

针对具体数据类型的操作,相关的方法需要首先获取对应的数据类型,获取相应数据类型的操作方法是 opsForXXX

调用该方法就可以将数据存储到 Redis 中去了。

k1 前面的字符是由于使用了 RedisTemplate 导致的,RedisTemplate 对 key 进行序列化之后的结果。

RedisTemplate 中,key 默认的序列化方案是 JdkSerializationRedisSerializer 。

而在 StringRedisTemplate 中,key 默认的序列化方案是 StringRedisSerializer ,因此,如果使用 StringRedisTemplate ,默认情况下 key 前面不会有前缀。

不过开发者也可以自行修改 RedisTemplate 中的序列化方案,如下:

@Service
public class HelloService {
@Autowired
RedisTemplate redisTemplate;
public void hello() {
redisTemplate.setKeySerializer(new StringRedisSerializer());
ValueOperations ops = redisTemplate.opsForValue();
ops.set("k1", "v1");
Object k1 = ops.get("k1");
System.out.println(k1);
}
}

当然也可以直接使用 StringRedisTemplate:

@Service
public class HelloService {
@Autowired
StringRedisTemplate stringRedisTemplate;
public void hello2() {
ValueOperations ops = stringRedisTemplate.opsForValue();
ops.set("k2", "v2");
Object k1 = ops.get("k2");
System.out.println(k1);
}
}

另外需要注意 ,Spring Boot 的自动化配置,只能配置单机的 Redis ,如果是 Redis 集群,则所有的东西都需要自己手动配置。

2、Spring Cache

2.1 引入依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.2 基本配置

简单配置一下Redis,配置一下Cache。

spring.redis.port=6380
spring.redis.host=192.168.66.128 spring.cache.cache-names=c1

在配置类上添加如下代码,表示开启缓存:

@SpringBootApplication
@EnableCaching
public class RediscacheApplication {
public static void main(String[] args){
SpringApplication.run(RediscacheApplication.class, args);
}
}

完成了这些配置之后,Spring Boot就会自动帮我们在后台配置一个RedisCacheManager,相关的配置是在org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration类中完成的。

2.3 缓存使用

2.3.1 @CacheConfig

这个注解在类上使用,用来描述该类中所有方法使用的缓存名称,当然也可以不使用该注解,直接在具体的缓存注解上配置名称,示例代码如下:

@Service
@CacheConfig(cacheNames = "c1")
public class UserService {
}

2.3.2 @Cacheable

这个注解一般加在查询方法上,表示将一个方法的返回值缓存起来,默认情况下,缓存的key就是方法的参数,缓存的value就是方法的返回值。示例代码如下:

@Cacheable(key = "#id")
public User getUserById(Integer id,String username) {
System.out.println("getUserById");
return getUserFromDBById(id);
}

当有多个参数时,默认就使用多个参数来做key,如果只需要其中某一个参数做key,则可以在@Cacheable注解中,通过key属性来指定key,如上代码就表示只使用id作为缓存的key,如果对key有复杂的要求,可以自定义keyGenerator。

2.3.3 @CachePut

这个注解一般加在更新方法上,当数据库中的数据更新后,缓存中的数据也要跟着更新,使用该注解,可以将方法的返回值自动更新到已经存在的key上,示例代码如下:

@CachePut(key = "#user.id")
public User updateUserById(User user) {
return user;
}

2.3.4 @CacheEvict

这个注解一般加在删除方法上,当数据库中的数据删除后,相关的缓存数据也要自动清除,该注解在使用的时候也可以配置按照某种条件删除(condition属性)或者或者配置清除所有缓存(allEntries属性),示例代码如下:

@CacheEvict()
public void deleteUserById(Integer id) {
//在这里执行删除操作, 删除是去数据库中删除
}

3、直接使用 Jedis 或者 其他的客户端工具来操作 Redis

(一)Spring-Boot-操作-Redis的更多相关文章

  1. Spring Boot + Mybatis + Redis二级缓存开发指南

    Spring Boot + Mybatis + Redis二级缓存开发指南 背景 Spring-Boot因其提供了各种开箱即用的插件,使得它成为了当今最为主流的Java Web开发框架之一.Mybat ...

  2. spring boot 结合Redis 实现工具类

    自己整理了 spring boot 结合 Redis 的工具类引入依赖 <dependency> <groupId>org.springframework.boot</g ...

  3. (转)spring boot整合redis

    一篇写的更清晰的文章,包括redis序列化:http://makaidong.com/ncjava/330749_5285125.html 1.项目目录结构 2.引入所需jar包 <!-- Sp ...

  4. 【redis】4.spring boot集成redis,实现数据缓存

    参考地址:https://spring.io/guides/gs/messaging-redis/ ================================================== ...

  5. (35)Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】

    [本文章是否对你有用以及是否有好的建议,请留言] 本文章牵涉到的技术点比较多:Spring Data JPA.Redis.Spring MVC,Spirng Cache,所以在看这篇文章的时候,需要对 ...

  6. Spring Boot 2.X(六):Spring Boot 集成Redis

    Redis 简介 什么是 Redis Redis 是目前使用的非常广泛的免费开源内存数据库,是一个高性能的 key-value 数据库. Redis 与其他 key-value 缓存(如 Memcac ...

  7. Spring Boot2 系列教程(二十六)Spring Boot 整合 Redis

    在 Redis 出现之前,我们的缓存框架各种各样,有了 Redis ,缓存方案基本上都统一了,关于 Redis,松哥之前有一个系列教程,尚不了解 Redis 的小伙伴可以参考这个教程: Redis 教 ...

  8. 【spring boot】【redis】spring boot基于redis的LUA脚本 实现分布式锁

    spring boot基于redis的LUA脚本 实现分布式锁[都是基于redis单点下] 一.spring boot 1.5.X 基于redis 的 lua脚本实现分布式锁 1.pom.xml &l ...

  9. Spring Boot与Redis的集成

    Redis是一个完全开源免费的.遵守BSD协议的.内存中的数据结构存储,它既可以作为数据库,也可以作为缓存和消息代理.因其性能优异等优势,目前已被很多企业所使用,但通常在企业中我们会将其作为缓存来使用 ...

  10. Spring Boot学习笔记——Spring Boot与Redis的集成

    一.添加Redis缓存 1.添加Redis起步依赖 在pom.xml中添加Spring Boot支持Redis的依赖配置,具体如下: <dependency> <groupId> ...

随机推荐

  1. 使用iconv进行文件编码转换

    在使用科大讯飞的时候输出字符是gbk字符编码.但是在ubuntu下gbk显示乱码,故用iconv进行字符编码转换.下面是我整理的字符编码转化的程序案例.从gbk2312转换到utf-8. 程序代码: ...

  2. 数据接口请求异常:parsererror

    问题一:直接拿别人的文件放在本地打开 如下图 原因:这是提示"交叉源请求仅支持协议方案:HTTP.数据.Chrome.Chrome扩展.HTTPS." 也就是你不能用本地文件打开, ...

  3. 一致性HASH算法在分布式应用场景使用

    其实不管redis还好,Mysql也好 这种数据存储介质,在分布式场景中都存在共同问题:即集群场景下服务路由.比如redis集群场景下,原本我们分3主3从部署.但万一有一天出现访问量暴增或其中一台机器 ...

  4. .NET C#中处理Url中文编码问题

    近些日子在做一个用C#访问webservise的程序,由于需要传递中文参数去请求网站,所以碰到了中文编码问题.我们知道像百度这种搜索引擎中,当用户输入中文关键字后,它会把中文转码,以确保在Url中不会 ...

  5. ContactCollections Design Report

    通讯录的设计采用了分层+接口+面向对象+文件操作+方法实现 分三层实现,共使用了四个包,实现业务数据访问和界面的分离     contactaccess包实现对文件的访问         包括数据访问 ...

  6. 【高精度】计算2的N次方

    题目相关 [题目描述] 任意给定一个正整数N(N≤100),计算2的n次方的值. [输入] 输入一个正整数N. [输出] 输出2的N次方的值. [输入样例] 5 [输出样例] 32 分析 本题考察的是 ...

  7. TR2021_0000偶发数据库连接异常问题排查

    [问题描述] 数据库连接异常是很难排查的一类问题.因为它牵涉到应用端,网络层和服务器端.任何一个组件异常,都会导致数据库连接失败.开发遇到数据库连接不上的问题,都会第一时间找DBA来协助查看,DBA除 ...

  8. Laya 小游戏通用框架设计理念

    当前在用laya做小游戏开发,做了几个项目,总结了一下游戏中所需要的一些模块,大概理了一下,然后写成一套自己习惯使用的框架 总结了一下其中的模块 大概要分为一下模块 1.Base 模块    存放一些 ...

  9. qmake奇淫技巧之字符串宏定义

    阅读本文大概需要3.3分钟 我们平时在软件开发过程中需要定义一些宏,以便在代码中调用,这样每次不需要修改代码,只需要修改外部编译命令就可以得到想要的参数,非常方便 比如我们想在软件介绍中显示软件版本, ...

  10. leetcode刷题录-1395

    目录 题目 思考过程 查看别人分享的思路 总结 题目 题目地址:https://leetcode-cn.com/problems/count-number-of-teams/ n 名士兵站成一排.每个 ...