发布时间:2021-10-30作者:laosun阅读(824)
我们先创建个简单的springboot web项目
如下图所示:
创建完成后,我们导入redis jar包
<!-- 导入redis依赖包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
application.properties
server.port=8080 spring.redis.database=0 spring.redis.timeout=10000 spring.redis.password=redis@11.. spring.redis.pool.max-idle=8 spring.redis.pool.min-idle=0 spring.redis.pool.max-active=8 spring.redis.pool.max-wait=-1 # 哨兵的主master名字 spring.redis.sentinel.master=mymaster # 哨兵的密码 spring.redis.sentinel.password=redis@11.. # 三个哨兵的链接方式 spring.redis.sentinel.nodes=192.168.0.124:26379,192.168.0.124:26380,192.168.0.124:26381
HelloController.java
import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * redis sentinel 高可用测试 * * @author sun * @date 2021/10/29 17:16 */ @RestController @RequestMapping("hello") @Slf4j public class HelloController { @Autowired private StringRedisTemplate stringRedisTemplate; @RequestMapping("index") public Object index(@RequestParam(defaultValue = "redisKey") String key, @RequestParam(defaultValue = "redisValue") String value) { log.info("请求到达"); stringRedisTemplate.opsForValue().set(key, value); Object redisValue = stringRedisTemplate.opsForValue().get(key); log.info("key:{} - value:{}", key, redisValue); return value; } }
测试类:
@SpringBootTest @Slf4j class RedisDemoApplicationTests { @Autowired private StringRedisTemplate stringRedisTemplate; @Test void testSetRedis() { String key = "rediskey"; stringRedisTemplate.opsForValue().set(key, "Hello World!"); String value = stringRedisTemplate.opsForValue().get(key); log.info("key:{} - value:{}", key, value); } @Test void contextLoads() { } }
版权属于: 技术客
原文地址: https://www.sunjs.com/article/detail/662132918a6d4405ac6ff8db1bd97028.html
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
关键字: Java 源码 redis springboot