Redis是干啥的,我就不在这说了,我说的肯定很肤浅,不出意外,你们会觉得我说了和没说一样,所以大家还是去找度娘靠谱。
下面分不同情况来设置:(我这里是yml配置,properties和这个类似)
一、单机redis配置
适用于:生产、测试、开发 redis 均为单机
redis:
# Redis数据库索引(默认为0)
database: 0
host: xxx.xxx.xx.xx
port: 6379
# Redis服务器连接密码(默认为空)
password:
# 连接超时时间(毫秒)
timeout: 5000ms
jedis:
pool:
#最大连接数据库连接数,设 0 为没有限制
max-active: 8
#最大等待连接中的数量,设 0 为没有限制
max-idle: 8
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
max-wait: -1ms
#最小等待连接中的数量,设 0 为没有限制
min-idle: 0
lettuce:
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
# 连接池中的最大空闲连接
max-idle: 8
# 连接池中的最小空闲连接
min-idle: 0
shutdown-timeout: 100ms
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.net.UnknownHostException;
/**
* @Author: yansf
* @Description:redis配置
* @Date: 3:18 PM 2018/4/18
* @Modified By:
*/
@Configuration
@ConditionalOnClass(RedisTemplate.class)
public class RedisConfig {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setDefaultSerializer(new RedisJsonSerializer<>());
template.afterPropertiesSet();
//UserUtil.setCache(template);
return template;
}
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
二、redis集群
适用于:各环境均为redis集群
只需要将单机配置中的host替换成cluster: nodes:如下图:(对就是这么简单👏)RedisConfig类不需要动
三、同时支持单机和集群模式(重点来了👉👉👉👉)
适用于:既有集群又有单机(eg:线上是redis集群,测试/开发是单例模式)
虽然是集群,但是还是用host,如下图:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.MapPropertySource;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: yansf
* @Description:redis配置
* @Date: 3:18 PM 2018/4/18
* @Modified By:
*/
@Configuration
@ConditionalOnClass(RedisTemplate.class)
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.max-redirects}")
private String redirects;
@Value("${spring.redis.timeout}")
private String timeout;
@Value("${spring.redis.password}")
private String password;
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setDefaultSerializer(new RedisJsonSerializer<>());
template.afterPropertiesSet();
//UserUtil.setCache(template);
return template;
}
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
/**
* @Author: yansf
* @Description:redis集群配置
* @Date: 17:45 2020/4/28
* @Modified By:
*/
@Bean
public RedisClusterConfiguration getClusterConfiguration() {
if (host.split(",").length > 1) {
//如果是host是集群模式的才进行以下操作
Map<String, Object> source = new HashMap<String, Object>();
source.put("spring.redis.cluster.nodes", host);
source.put("spring.redis.cluster.timeout", timeout.replace("ms",""));
source.put("spring.redis.cluster.max-redirects", redirects);
source.put("spring.redis.cluster.password", password);
return new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source));
} else {
return null;
}
}
/**
* @Author: yansf
* @Description:集群遍历
* @Date: 17:50 2020/4/28
* @Modified By:
*/
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
if (host.split(",").length == 1) {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(host.split(":")[0]);
factory.setPort(Integer.valueOf(host.split(":")[1]));
factory.setPassword(password);
factory.setTimeout(Integer.parseInt(timeout.replace("ms","")));
return factory;
} else {
JedisConnectionFactory jcf = new JedisConnectionFactory(getClusterConfiguration());
jcf.setPassword(password); //集群的密码认证
return jcf;
}
}
}
然后测试一下就可以了:
/**
* @Author: yansf
* @Description:redis测试
* @Date: 8:29 PM 2019/1/14
* @Modified By:
*/
@GetMapping(value = "/redis")
public void getredis() {
stringRedisTemplate.opsForValue().set("**:**:ysfTest1:", "hello redis cluster");
// stringRedisTemplate.expireAt();
logger.info("=========" + stringRedisTemplate.opsForValue().get("**:**:ysfTest1:"));
redisTemplate.opsForValue().set("**:**:ysfTest2:", DateUtil.getNow());
logger.info("=========" + redisTemplate.opsForValue().get("**:**:ysfTest2:"));
}