SpringBoot & Redis

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

SpringBoot入门系列

三步实施

  • pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.1.2.RELEASE</version>
</dependency>
  • application.properties
# 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三者的关系
LettuceJedis 的都是连接Redis Server的客户端程序。
Jedis在实现上是直连redis server,多线程环境下非线程安全,除非使用连接池,为每个Jedis实例增加物理连接。
Lettuce基于Netty的连接实例(StatefulRedisConnection),可以在多个线程间并发访问,且线程安全,满足多线程环境下的并发访问,同时它是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例。
spring-boot-data-redis 内部实现了对LettuceJedis两个客户端的封装,默认使用的是Lettuce

连接池

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

  • application.properties
#连接池最大连接数(使用负值表示没有限制)
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

  • pom.xml

需要引入commons-pools

<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

参考

猜你喜欢

转载自blog.csdn.net/weixin_34239592/article/details/86936920