maven配置
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.11.1</version> </dependency>
application.yaml配置
spring:application:name: daisy-web-testredis:host: 127.0.0.1port: 6379password: 123456lettuce:pool:max-active: 10max-idle: 10min-idle: 1time-between-eviction-runs: 10senabled: truesentinel:master: mymasterpassword: 123456nodes: 192.168.2.168:26379,192.168.2.168:26380,192.168.2.168:26381
RedisConfig配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {//大多数情况,都是选用<String, Object>RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(redisConnectionFactory);StringRedisSerializer serializer = new StringRedisSerializer();template.setKeySerializer(serializer);template.setHashKeySerializer(serializer);return template;}}
cotroller测试
import cn.hutool.core.lang.UUID;
import com.daisy.web.test.util.redis.CacheUtilManager;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.hutool.core.lang.UUID;
import com.daisy.web.test.util.redis.CacheUtilManager;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.concurrent.TimeUnit;@RestController
@RequestMapping("/redis")
@Log4j2
public class RedisController {@Autowiredprivate RedisTemplate redisTemplate;/*** http://127.0.0.1:8888/redis/set* @return*/@RequestMapping("/set")public String user() {try {for (int i = 0; i < Integer.MAX_VALUE; i++) {TimeUnit.SECONDS.sleep(2);String key="name";Object o = redisTemplate.opsForValue().get(key);System.out.println("old value : "+o);String value= java.util.UUID.randomUUID().toString();redisTemplate.opsForValue().set(key, value);Object o2 = redisTemplate.opsForValue().get(key);System.out.println("new value : "+o2);}return UUID.randomUUID().toString();} catch (Exception e) {e.printStackTrace();return "error";}}}
启动项目访问
测试地址 http://127.0.0.1:8888/redis/set
查看日志
异常测试
停掉集群中的master节点,观察日志,发现报错,然后从节点变为主节点后又连接成功,可以继续使用