Spring Boot - 数据库操作之Redis

2018-11-02  本文已影响14人  yuanzicheng

Sprint Data也提供了对Redis的支持,单节点的Redis集成也非常简单。

添加依赖

compile('org.springframework.boot:spring-boot-starter-data-redis:1.5.7.RELEASE')

再application.properties中配置redis相关项

# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.101.129
# 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快速操作Redis

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

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

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

}

实际生产中,很少会使用单节点的Redis,可能会使用sentinel或者cluster,集成比单节点Redis稍微复杂一些。

# redis cluster
spring.redis.cluster.nodes=127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384
spring.redis.cluster.timeout=5
spring.redis.cluster.max-redirects=3

如果要操作非String类型的数据(如:Hash等),可以使用RedisTemplate

上一篇 下一篇

猜你喜欢

热点阅读