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集群运行及选举具体运作方式,可以参考这篇 >> 博文