Spring Boot & Redis

/ Java / 没有评论 / 1865浏览

本文接着前面的继续,介绍如何快速接入Redis

Spring Boot入门系列

三步实施

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.1.2.RELEASE</version>
</dependency>
# Redis服务器地址
spring.redis.host=192.168.58.100
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=123456
# 连接超时时间(毫秒)
spring.redis.timeout=3000

这种方式也支持集群模式的服务器

@Resource
private RedisTemplate<String, String> redisTemplate;

@GetMapping("access/{id}")
public int access(@PathVariable("id") int id) {
    final Long count = redisTemplate.opsForValue().increment(Integer.toString(id));
    assert count != null;
    return (int)count.longValue();
}

Lettuce&Jedis&spring-boot-starter-data-redis三者的关系

连接池

多线程环境下,使用池化技术,提高性能。对Jedis来说更是必须,否则还会出现数据错误。

#连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.6.0</version>
</dependency>

集群

# 集群节点(多个节点使用逗号分隔)
spring.redis.cluster.nodes=192.168.58.100:6379,192.168.58.101:6379
# Redis服务器连接密码(默认为空)
spring.redis.password=123456
# 连接超时时间(毫秒)
spring.redis.timeout=3000

参考