springboot整合redis

springboot整合redis

添加pom.xml依赖


org.springframework.boot
spring-boot-starter-redis
1.2.5.RELEASE

参数设置

在application.properties加入设置

REDIS (RedisProperties)

Redis数据库索引(默认为0)

spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0

使用StringRedisTemplate测试访问

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootredisApplicationTests {

@Autowired
private StringRedisTemplate stringRedisTemplate;

@Test
public void stringRedisTest() throws Exception {
stringRedisTemplate.opsForValue().set("redisKey", "redisValue");
Assert.assertEquals("redisValue", stringRedisTemplate.opsForValue().get("redisKey"));
}

存储对象

除了String类型,实战中我们还经常会在Redis中存储对象,这时候我们就会想是否可以使用类似RedisTemplate<String, User>来初始化并进行操作。但是Spring Boot并不支持直接使用,需要我们自己实现RedisSerializer接口来对传入对象进行序列化和反序列化,下面我们通过一个实例来完成对象的读写操作。

1. 创建对象

没啥好说的,创建User.class

2. 实现对象的序列化接口

public class RedisObjectSerializer implements RedisSerializer

posted @ 2018-05-24 19:24  binfoo  阅读(150)  评论(0)    收藏  举报