docker方式 进行 redis + redis sentinel 主从节点+哨兵模式 集群部署使用

redis节点和sentinel节点应该是大于等于3的奇数个,以便于选举投票和有可选择性

redis的docker-compose配置:

version: '3.1'
services:
  master:
    image: redis
    container_name: redis-master
    restart: always
    ports:
      - 6379:6379

  slave1:
    image: redis
    container_name: redis-slave-1
    restart: always
    ports:
      - 6380:6379
    command: redis-server --slaveof redis-master 6379

  slave2:
    image: redis
    container_name: redis-slave-2
    restart: always
    ports:
      - 6381:6379
    command: redis-server --slaveof redis-master 6379

redis-sentinel的docker-compose配置:

version: '3.1'
services:
  sentinel1:
    image: redis
    container_name: redis-sentinel-1
    restart: always
    ports:
      - 26379:26379
    command: redis-sentinel /usr/local/etc/redis/sentinel.conf
    volumes:
      - ./sentinel1.conf:/usr/local/etc/redis/sentinel.conf

  sentinel2:
    image: redis
    container_name: redis-sentinel-2
    restart: always
    ports:
      - 26380:26379
    command: redis-sentinel /usr/local/etc/redis/sentinel.conf
    volumes:
      - ./sentinel2.conf:/usr/local/etc/redis/sentinel.conf

  sentinel3:
    image: redis
    container_name: redis-sentinel-3
    restart: always
    ports:
      - 26381:26379
    command: redis-sentinel /usr/local/etc/redis/sentinel.conf
    volumes:
      - ./sentinel3.conf:/usr/local/etc/redis/sentinel.conf

sentinel.conf 配置(自定义命名+ip+端口+选举最大数): 

port 26379
dir /tmp
sentinel monitor mymaster 192.168.73.135 6379 2
sentinel down-after-milliseconds mymaster 30000
sentinel parallel-syncs mymaster 1
sentinel failover-timeout mymaster 180000
sentinel deny-scripts-reconfig yes

把sentinel.conf复制三份,分别命名为1,2,3(其内容在sentinel容器启动后会自动变更):

添加项目application.properties配置:

# Redis主节点名称
spring.redis.sentinel.master=mymaster
# 连接的redis哨兵节点(你连接哨兵,哨兵帮你连接redis)
spring.redis.sentinel.nodes=192.168.73.135:26379

# 连接池最大连接数
spring.redis.lettuce.pool.max-active=20
# 连接池最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-wait=-1
# 连接池最大空闲连接数
spring.redis.lettuce.pool.max-idle=5
# 连接池最小空闲连接数
spring.redis.lettuce.pool.min-idle=0

 如果没有搭建redis集群,只是单一redis服务器,则配置如下:

# Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0

需要两个pom依赖:

        <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- spring2.X集成redis所需common-pool2-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.6.0</version>
        </dependency>

增加redis配置类:

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

使用方式:

(一)在对应方法上添加注解:(如@Cacheable首次时查询数据库并缓存,之后在数据未做变动和未过期之前优先缓存读取)

    @Cacheable(value = "banner",key = "'getBannerList'")
    @Override
    public List<CrmBanner> getBannerList() {
        QueryWrapper<CrmBanner> bannerQueryWrapper = new QueryWrapper<>();
        bannerQueryWrapper.orderByDesc("gmt_create");
        bannerQueryWrapper.last(" limit 3");
        List<CrmBanner> bannerList = baseMapper.selectList(bannerQueryWrapper);
        return bannerList;
    }

相应注解作用可以参考这篇 >> 博文 

效果如下:

(二)作为微服务应用对外提供存取服务:

接口:

public interface RedisService {

    public void put(String key,Object value,long seconds);

    public Object get(String key);
}

实现类:

import com.gbx.spring.cloud.demo.service.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl implements RedisService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void put(String key, Object value, long seconds) {
        redisTemplate.opsForValue().set(key,value,seconds, TimeUnit.SECONDS);
    }

    @Override
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }
}

api接口(Restcontroller):

import com.gbx.spring.cloud.demo.service.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisController {

    @Autowired
    private RedisService redisService;

    /**
     * 缓存键值对数据
     * @param key
     * @param value
     * @param seconds 过期时间
     */
    @RequestMapping(value = "put",method = RequestMethod.POST)
    public String put(String key,String value,long seconds){
        redisService.put(key,value,seconds);
        return "ok";
    }

    /**
     * 依靠键取出缓存数据
     * @param key
     * @return
     */
    @RequestMapping(value = "get",method = RequestMethod.GET)
    public String get(String key){
        String json = null;

        Object o = redisService.get(key);
        if (o != null){
            json= (String)o;
        }
        return json;
    }
}

其他应用可以通过feign调用功能:

import com.gbx.spring.cloud.demo.service.sso.service.consumer.fallback.RedisServiceFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(value = "spring-cloud-demo-service-redis",fallback = RedisServiceFallback.class)
public interface RedisService {

    @RequestMapping(value = "put",method = RequestMethod.POST)
    public String put(@RequestParam(value = "key") String key,@RequestParam(value = "value")String value,@RequestParam(value = "seconds")long seconds);

    @RequestMapping(value = "get",method = RequestMethod.GET)
    public String get(@RequestParam(value = "key")String key);
}

至于redis sentinel集群运行及选举具体运作方式,可以参考这篇 >> 博文

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Docker配置Redis哨兵模式时,可以按照以下步骤进行操作: 1. 首先,确保已经安装了DockerDocker Compose。 2. 创建一个新的目录,用于存放Redis配置文件和Docker Compose文件。 3. 在该目录下创建一个名为`docker-compose.yml`的文件,并在其中编写以下内容: ```yaml version: '3' services: redis-master: image: redis container_name: redis-master ports: - "6379:6379" volumes: - ./redis-master.conf:/usr/local/etc/redis/redis.conf command: redis-server /usr/local/etc/redis/redis.conf redis-slave1: image: redis container_name: redis-slave1 ports: - "6380:6379" volumes: - ./redis-slave1.conf:/usr/local/etc/redis/redis.conf command: redis-server /usr/local/etc/redis/redis.conf redis-slave2: image: redis container_name: redis-slave2 ports: - "6381:6379" volumes: - ./redis-slave2.conf:/usr/local/etc/redis/redis.conf command: redis-server /usr/local/etc/redis/redis.conf redis-sentinel1: image: redis container_name: redis-sentinel1 ports: - "26379:26379" volumes: - ./sentinel1.conf:/usr/local/etc/redis/sentinel.conf command: redis-sentinel /usr/local/etc/redis/sentinel.conf --sentinel redis-sentinel2: image: redis container_name: redis-sentinel2 ports: - "26380:26379" volumes: - ./sentinel2.conf:/usr/local/etc/redis/sentinel.conf command: redis-sentinel /usr/local/etc/redis/sentinel.conf --sentinel redis-sentinel3: image: redis container_name: redis-sentinel3 ports: - "26381:26379" volumes: - ./sentinel3.conf:/usr/local/etc/redis/sentinel.conf command: redis-sentinel /usr/local/etc/redis/sentinel.conf --sentinel ``` 4. 在同一目录下创建以下配置文件: - `redis-master.conf`:Redis节点配置文件,内容如下: ``` bind 0.0.0.0 port 6379 daemonize yes ``` - `redis-slave1.conf`:Redis节点1的配置文件,内容如下: ``` bind 0.0.0.0 port 6379 daemonize yes slaveof redis-master 6379 ``` - `redis-slave2.conf`:Redis节点2的配置文件,内容如下: ``` bind 0.0.0.0 port 6379 daemonize yes slaveof redis-master 6379 ``` - `sentinel1.conf`:Redis哨兵1的配置文件,内容如下: ``` bind 0.0.0.0 port 26379 sentinel monitor mymaster redis-master 6379 2 sentinel down-after-milliseconds mymaster 5000 sentinel failover-timeout mymaster 10000 sentinel parallel-syncs mymaster 1 ``` - `sentinel2.conf`:Redis哨兵2的配置文件,内容如下: ``` bind 0.0.0.0 port 26379 sentinel monitor mymaster redis-master 6379 2 sentinel down-after-milliseconds mymaster 5000 sentinel failover-timeout mymaster 10000 sentinel parallel-syncs mymaster 1 ``` - `sentinel3.conf`:Redis哨兵3的配置文件,内容如下: ``` bind 0.0.0.0 port 26379 sentinel monitor mymaster redis-master 6379 2 sentinel down-after-milliseconds mymaster 5000 sentinel failover-timeout mymaster 10000 sentinel parallel-syncs mymaster 1 ``` 5. 打开终端,进入到该目录,并执行以下命令启动Redis容器: ``` docker-compose up -d ``` 这将启动一个包含Redis节点、两个从节点和三个哨兵节点Docker容器。 现在,你已经成功配置Redis哨兵模式。你可以通过访问`localhost:6379`来访问Redis节点,`localhost:6380`和`localhost:6381`来访问两个从节点,以及`localhost:26379`、`localhost:26380`和`localhost:26381`来访问三个哨兵节点

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值