Spring Boot 提供了对 Redis 集成的组件包:spring-boot-starter-data-redis,spring-boot-starter-data-redis 依赖于spring-data-redis 和 lettuce 。
org.springframework.boot
spring-boot-starter-data-redis
1.2 参数配置
在 application.properties 中加入Redis服务端的相关配置 :
#redis配置
#Redis服务器地址
spring.redis.host=127.0.0.1
#Redis服务器连接端口
spring.redis.port=6379
#Redis数据库索引(默认为0)
spring.redis.database=0
#连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=50
#连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=3000ms
#连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=20
#连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=2
#连接超时时间(毫秒)
spring.redis.timeout=5000ms
其中 spring.redis.database 的配置通常使用0即可,Redis 在配置的时候可以设置数据库数量,默认为16,可以理解为数据库的 schema
1.3 测试访问
通过编写测试用例,举例说明如何访问Redis。
@RunWith(SpringRunner.class)
@SpringBootTest
public class FirstSampleApplicationTests {
@Autowired
StringRedisTemplate stringRedisTemplate;
@Test
public void test() throws Exception {
// 保存字符串
stringRedisTemplate.opsForValue().set(“name”, “chen”);
Assert.assertEquals(“chen”, stringRedisTemplate.opsForValue().get(“name”));
}
}
上面的案例通过自动配置的 StringRedisTemplate
对象进行 redis 的对写操作,从对象命名就可注意到支持的是 string 类型,如果有用过 spring-data-redis 的开发者一定熟悉 RedisTemplate<K,V>
接口,StringRedisTemplate 就相当于 RedisTemplate<String, String>
的实现。
除了 String 类型,实战中经常会在 redis 中储存对象,我们就要在储存对象时对对象进行序列化。下面通过一个实例来完成对象的对写操作。