Redis是一个开源(BSD许可)的、内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。 它支持多种类型的数据结构,如字符串(strings)、散列(hashes)、列表(lists)、集合(sets)、有序集合(sorted sets)与范围查询、bitmaps、hyperloglogs和地理空间(geospatial)索引半径查询。 Redis内置了复制(replication)、LUA脚本(Lua scripting)、LRU驱动事件(LRU eviction)、事务(transactions)和不同级别的磁盘持久化(persistence), 并通过Redis哨兵(Sentinel)和自动分区(Cluster)提供高可用性(high availability)
org.springframework.boot
spring-boot-starter-data-redis
可以看到,会自动添加spring-data-redis和lettuce(netty实现)的redis客户端
查看spring-boot-autoconfigure-2.7.5.jar,,可以看到:
package org.springframework.boot.autoconfigure.data.redis;
.....省略部分......
@AutoConfiguration
@ConditionalOnClass({RedisOperations.class})
@EnableConfigurationProperties({RedisProperties.class})
@Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
public class RedisAutoConfiguration {
public RedisAutoConfiguration() {
}
@Bean
@ConditionalOnMissingBean(
name = {"redisTemplate"}
)
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public RedisTemplate
查看RedisProperties配置类,redis的配置由spring.redis开头的配置进行配置的
.....省略部分......
@ConfigurationProperties(
prefix = "spring.redis"
)
public class RedisProperties {
.....省略部分......
}
我们再来看LettuceConnectionConfiguration这个配置类,可以看到
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnClass({RedisClient.class})
@ConditionalOnProperty(
name = {"spring.redis.client-type"},
havingValue = "lettuce",
matchIfMissing = true
)
class LettuceConnectionConfiguration extends RedisConnectionConfiguration {
.....省略部分......
@Bean
@ConditionalOnMissingBean({RedisConnectionFactory.class})
LettuceConnectionFactory redisConnectionFactory(ObjectProvider builderCustomizers, ClientResources clientResources) {
LettuceClientConfiguration clientConfig = this.getLettuceClientConfiguration(builderCustomizers, clientResources, this.getProperties().getLettuce().getPool());
return this.createLettuceConnectionFactory(clientConfig);
}
.....省略部分......
}
我们再来看JedisConnectionConfiguration这个配置类,可以看到
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnClass({GenericObjectPool.class, JedisConnection.class, Jedis.class})
@ConditionalOnMissingBean({RedisConnectionFactory.class})
@ConditionalOnProperty(
name = {"spring.redis.client-type"},
havingValue = "jedis",
matchIfMissing = true
)
class JedisConnectionConfiguration extends RedisConnectionConfiguration {
......省略部分......
@Bean
JedisConnectionFactory redisConnectionFactory(ObjectProvider builderCustomizers) {
return this.createJedisConnectionFactory(builderCustomizers);
}
......省略部分......
}
说明:
# 格式:redis://username:password@IP:Port
spring.redis.url=redis://default:[email protected]:6379
# 单独指定redis各配置参数
# spring.redis.username=default
# spring.redis.password=redis123
# spring.redis.host=192.168.28.12
# spring.redis.port=6379
spring.redis.client-type=lettuce
# 连接池同时活跃的最大连接数
spring.redis.lettuce.pool.max-active=10
# 连接池最小空闲连接数
spring.redis.lettuce.pool.min-idle=5
下面做了如下操作:
package com.hh.springboottest;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
@Slf4j
@SpringBootTest
public class MyApplicationTest {
@Autowired
RedisTemplate redisTemplate;
@Autowired
RedisConnectionFactory redisConnectionFactory;
@Test
public void queryDataTest() {
ValueOperations operations = redisTemplate.opsForValue();
operations.set("redis-key", "hello world");
String redisKey = operations.get("redis-key");
log.info("获取到的redis-key: {}", redisKey);
// 对redis的key的value进行加1
redisTemplate.opsForValue().increment("increment-key");
log.info("当前使用的redis客户端是: {}", redisConnectionFactory.getConnection());
}
}
运行程序,结果如下:
2022-11-20 07:32:05.096 INFO 12476 --- [ main] com.hh.springboottest.MyApplicationTest : 获取到的redis-key: hello world
2022-11-20 07:32:05.101 INFO 12476 --- [ main] com.hh.springboottest.MyApplicationTest : 当前使用的redis客户端是: org.springframework.data.redis.connection.lettuce.LettuceConnection@57466fb7
2022-11-20 07:32:05.288 INFO 12476 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closing ...
2022-11-20 07:32:05.296 INFO 12476 --- [ionShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closed
在pom.xml添加依赖
redis.clients
jedis
然后修改application.properties参数文件。指定spring.redis.client-type=jedis。如下所示:
spring.redis.client-type=jedis
spring.redis.jedis.pool.max-active=10
默认使用JdkSerializationRedisSerializer序列化器,使用RedisTemplate保存User对象,在Redis中看到的是乱码,而且其它类型的框架也不能正确读取这个User对象。所以可以将User对象以json的方式进行保存
如果没有RedisTemplate,SpringBoot会自动添加一个默认的RedisTemplate。所以我们可以自己给IOC容器添加我们自定义的RedisTemplate,使用GenericJackson2JsonRedisSerializer
序列化器,允许Object类型的key和value,都可以被转为json进行存储。具体实现如下:
package com.hh.springboottest.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
@Configuration
public class RedisConfiguration {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory /*会自动注入进来*/) {
RedisTemplate template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}