1、pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、appliaction.properties
#redis配置
#Redis服务器地址
spring.redis.host=127.0.0.1
#Redis服务器连接端口
spring.redis.port=6379
#Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器连接密码
#spring.redis.password=123456
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=20
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=5000
上面配置是单机redis,如果是redis 集群
去掉单机配置
#spring.redis.host=127.0.0.1
#spring.redis.port=6379
#spring.redis.database=0
spring.redis.cluste.nodes: 192.168.20.102:7000,192.168.20.102:7001,192.168.20.102:7002,192.168.20.102:7003,192.168.20.102:7004,192.168.20.102:7005
#yml
spring:
redis:
cluster:
nodes: #这里上你Redis的各个端口号,也可以直接写在一行,逗号分开
- 192.168.20.102:7000
- 192.168.20.102:7001
- 192.168.20.102:7002
- 192.168.20.103:7003
- 192.168.20.103:7004
- 192.168.20.103:7005
3、StringRedisTemplate
@SpringBootTest
class RedisDemoApplicationTests {
@Autowired
StringRedisTemplate stringRedisTemplate;
@Test
void redisT() {
String key = "k1";
stringRedisTemplate.opsForValue().set(key, "hello-springboot");
String value = stringRedisTemplate.opsForValue().get(key);
System.out.println(key + ":" + value);
}
}
如果redis连接错误,则
需要改redis 的配置文件
1)修改 protected-mode yes 改为:protected-mode no
2)注释掉 #bind 127.0.0.1
修改 springboot 的配置文件
4)application.yml的redis配置中的spring.redis.timeout中连接超时时间(毫秒)中时间设置不能为0
5)redis如果没有密码,则需把密码的设置注释
StringRedisTemplate对Redis的五大常用数据类型都提供了方法
stringRedisTemplate.opsForValue(); [String(字符串)]
stringRedisTemplate.opsForList(); [List(列表)]
stringRedisTemplate.opsForSet(); [Set(集合)]
stringRedisTemplate.opsForHash(); [Hash(散列)]
stringRedisTemplate.opsForZSet(); [ZSet(有序集合)]
StringRedisTemplate 继承 RedisTemplate,上述方法也是继承而来的。
因为大多数针对Redis的操作都是基于字符串的,所以StringRedisTemplate 是一个专用的类,该类可以最小化其更通用的模板的配置,特别是在序列化程序方面。
https://docs.spring.io/spring-data/redis/docs/2.5.1/api/org/springframework/data/redis/core/ValueOperations.html
https://docs.spring.io/spring-data/redis/docs/2.5.1/api/org/springframework/data/redis/core/ListOperations.html
https://docs.spring.io/spring-data/redis/docs/2.5.1/api/org/springframework/data/redis/core/SetOperations.html
https://docs.spring.io/spring-data/redis/docs/2.5.1/api/org/springframework/data/redis/core/HashOperations.html
https://docs.spring.io/spring-data/redis/docs/2.5.1/api/org/springframework/data/redis/core/ZSetOperations.html
一般情况,对于简单的字符串处理,使用上述方法就能满足要求。
原文:https://www.cnblogs.com/zhanglw456/p/14838339.html