使用 Java 操作 Redis 的方案很多,Jedis 是目前较为流行的一种方案,除了 Jedis ,还有很多其他解决方案,如下:
除了这些方案之外,还有一个使用也相当多的方案,就是 Spring Data Redis。
在传统的 SSM 中,需要开发者自己来配置 Spring Data Redis ,这个配置比较繁琐,主要配置 3 个东西:连接池、连接器信息以及 key 和 value 的序列化方案。
在 Spring Boot 中,默认集成的 Redis 就是 Spring Data Redis,默认底层的连接池使用了 lettuce ,开发者可以自行修改为自己的熟悉的,例如 Jedis。
Spring Data Redis 针对 Redis 提供了非常方便的操作模板 RedisTemplate 。这是 Spring Data 擅长的事情,那么接下来我们就来看看 Spring Boot 中 Spring Data Redis 的具体用法。
方案一:Spring Data Redis创建工程
创建工程,引入 Redis 依赖:
创建成功后,还需要手动引入 commos-pool2 的依赖,因此最终完整的 pom.xml 依赖如下:
<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 + 连接池。
配置 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( RedisConnectionFac<em style="color:transparent">本文来源[email protected]搞@^&代*@码)网9</em>tory 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; } }