一、pom.xml引入依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency>
二、application.yml配置连接redis-sentinel集群:
spring: redis: lettuce: pool: max-active: 8 max-idle: 8 max-wait: -1ms min-idle: 0 sentinel: master: mymaster nodes: 192.168.64.132:26379,192.168.64.132:26380,192.168.64.132:26381
三、java类如下:
package com.example.redisdemo; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.util.concurrent.TimeUnit; @Repository public class RedisDao { @Resource private RedisTemplate<String, Object> redisTemplate; /** * 往Redis存数据 * @param key 主键 * @param value 值 * @param seconds 过期时间为秒 */ public void put(String key, Object value, long seconds){ redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS); } /** * 获取Redis内存中的数据 * @param key 主键 * @return */ public Object get(String key){ return redisTemplate.opsForValue().get(key); } }