redis哨兵模式搭建
详见redis经典三节点高可用哨兵模式集群搭建
redis1 192.168.1.101 6379(主)、6380(备)
redis2 192.168.1.102 6379(主)、6380(备)
redis3 192.168.1.103 6379(主)、6380(备)
sentinel.conf(配置中重点值)
port 26379
...
sentinel monitor codis-redis-1 192.168.1.101 6379 2
...
sentinel auth-pass codis-redis-1 admin123
...
xml引入相关jar
<!-- redis的starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>${springboot.version}</version>
<exclusions>
<exclusion>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</exclusion>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 引入jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.1.0</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
properties配置
#redis哨兵模式配置
spring.redis.timeout=6000
spring.redis.jedis.pool.max-active=100
spring.redis.jedis.pool.max-wait=6000
spring.redis.jedis.pool.max-idle=100
spring.redis.jedis.pool.min-idle=50
spring.redis.sentinel.master=codis-redis-1
spring.redis.sentinel.nodes=192.168.1.101:26379,192.168.1.102:26379,192.168.1.103:26379
spring.redis.sentinel.password=admin123
redis配置注解类
@Configuration
@EnableAutoConfiguration
public class RedisConfig {
private static Logger logger = getLogger(RedisConfig.class);
@Value("#{'${spring.redis.sentinel.nodes}'.split(',')}")
private List<String> nodes;
@Value("${spring.redis.sentinel.master}")
private String master;
@Value("${spring.redis.sentinel.password}")
private String password;
@Bean
@ConfigurationProperties(prefix="spring.redis")
public JedisPoolConfig getRedisConfig(){
JedisPoolConfig config = new JedisPoolConfig();
return config;
}
@Bean
public RedisSentinelConfiguration sentinelConfiguration(){
RedisSentinelConfiguration redisSentinelConfiguration = new RedisSentinelConfiguration();
//配置matser的名称
redisSentinelConfiguration.master(master);
//配置redis的哨兵sentinel
Set<RedisNode> redisNodeSet = new HashSet<>();
nodes.forEach(x->{
redisNodeSet.add(new RedisNode(x.split(":")[0],Integer.parseInt(x.split(":")[1])));
});
logger.info("redisNodeSet -->"+redisNodeSet);
redisSentinelConfiguration.setSentinels(redisNodeSet);
redisSentinelConfiguration.setPassword(password);
return redisSentinelConfiguration;
}
@Bean
public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig, RedisSentinelConfiguration sentinelConfig) {
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(sentinelConfig,jedisPoolConfig);
return jedisConnectionFactory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
RedisTemplate<String,Object> redisTemplate=new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory);
GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
// 设置值(value)的序列化采用FastJsonRedisSerializer。
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
// redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
// 设置键(key)的序列化采用StringRedisSerializer。
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
redis工具类
public interface RedisService {
boolean expire(String key, long time);
long getExpire(String key);
void remove(final String... keys);
void removePattern(final String pattern);
void remove(final String key);
boolean exists(final String key);
Object get(String key);
boolean set(String key, Object value);
boolean set(String key, Object value, long time);
long incr(String key, long delta) ;
long decr(String key, long delta);
}
@Service(CommonBaseConstant.SERVICE_REDIS)
public class RedisServiceImpl implements RedisService {
@Autowired
private RedisTemplate redisTemplate;
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
@Override
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
@Override
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 批量删除对应的value
*
* @param keys
*/
@Override
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
*
* @param pattern
*/
@Override
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0) {
redisTemplate.delete(keys);
}
}
/**
* 删除对应的value
*
* @param key
*/
@Override
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
@Override
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 缓存获取
*
* @param key 键
* @return 值
*/
@Override
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
@Override
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
@Override
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
*
* @param key 键
* @param delta 要增加几(大于0)
* @return 134
*/
@Override
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException(CommonBaseConstant.INCREMENTAL_FACTOR);
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
*
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
@Override
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException(CommonBaseConstant.DECREASING_FACTOR);
}
return redisTemplate.opsForValue().increment(key, -delta);
}
}
测试类
@RestController
@CrossOrigin
@RequestMapping("/test")
public class TestController {
private Logger logger = LogManager.getLogger(TestController.class);
@Autowired
private RedisService<String> redisService;
@RequestMapping(value = "/setRedisValue", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public JsonResult<String> setRedisValue(HttpServletRequest request) {
redisService.put("testKey", "hello redis", REDIS_DEFAULT_EXPIRE_SIX_HOURS_TIME);
return new JsonResult(SUCCESS_CODE, SUCCESS_MESSAGE, null);
}
@RequestMapping(value = "/getRedisValue", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public JsonResult<String> getRedisValue(HttpServletRequest request) {
Object obj = redisService.get("testKey");
return new JsonResult(SUCCESS_CODE, SUCCESS_MESSAGE, obj == null ? null : GsonUtils.gsonString(obj));
}
springboot—demo下载地址 https://download.csdn.net/download/qq_25073261/12327116