SringBoot 演示 redis 一主多从+哨兵模式 高可用模拟

发布时间:2021-10-30作者:laosun阅读(721)

SringBoot

    redis 主从复制模式

    redis 一主多从 + sentinel哨兵模式

    我们先创建个简单的springboot web项目

    如下图所示:

    Image

    Image

    创建完成后,我们导入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() {
        }
    
    }


0 +1

版权声明

 Java  源码  redis  springboot

 请文明留言

0 条评论