根据配置RedisProperties自动获取RedisConnectionFactory
#单点配置
spring.redis.host=192.168.1.1
spring.redis.port=6379 #哨兵配置
#spring.redis.sentinel.master=common
#spring.redis.sentinel.nodes=192.168.1.84:26379,192.168.1.85:26379
#spring.redis.password=123456 #集群配置
#spring.redis.cluster.nodes=192.168.1.24:6389,192.168.1.24:6479,192.168.1.24:6579
#spring.redis.password=123456
1.增加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>
1. org.springframework.boot.autoconfigure.data.redis.RedisProperties 会根据配置自动加载为一个bean
@ConfigurationProperties(prefix = "spring.redis") 2.RedisConfig
import com.google.common.base.Strings; import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig; /**
* Redis配置类
*/
@Slf4j
@Configuration
public class RedisConfig { @Bean(name = "JedisConnectionFactory")
public JedisConnectionFactory createJedisConnectionFactory(RedisProperties properties,
JedisPoolConfig poolConfig) {
JedisConnectionFactory factory;
RedisSentinelConfiguration sentinelConfig = getSentinelConfiguration(properties);
RedisClusterConfiguration clusterConfiguration = getClusterConfiguration(properties);
if (sentinelConfig != null) {
factory = new JedisConnectionFactory(sentinelConfig, poolConfig);
} else if (clusterConfiguration != null) {
factory = new JedisConnectionFactory(clusterConfiguration, poolConfig);
} else {
factory = new JedisConnectionFactory(poolConfig);
factory.setHostName(properties.getHost());
factory.setPort(properties.getPort());
factory.setDatabase(properties.getDatabase());
} if (!Strings.isNullOrEmpty(properties.getPassword())) {
factory.setPassword(properties.getPassword());
}
return factory;
} @Bean(name = "RedisConnectionFactory")
@Autowired
public RedisConnectionFactory createRedisConnectionFactory(
@Qualifier("JedisConnectionFactory") JedisConnectionFactory
factory) {
return factory;
} private static List<RedisNode> createSentinels(RedisProperties.Sentinel sentinel) {
List<RedisNode> nodes = new ArrayList<>();
for (String node : StringUtils.commaDelimitedListToStringArray(sentinel.getNodes())) {
String[] parts = StringUtils.split(node, ":");
Assert.state(parts.length == 2, "redis哨兵地址配置不合法!");
nodes.add(new RedisNode(parts[0], Integer.valueOf(parts[1])));
}
return nodes;
} private static RedisSentinelConfiguration getSentinelConfiguration(RedisProperties properties) {
RedisProperties.Sentinel sentinel = properties.getSentinel();
if (sentinel != null) {
RedisSentinelConfiguration config = new RedisSentinelConfiguration();
config.master(sentinel.getMaster());
config.setSentinels(createSentinels(sentinel));
return config;
}
return null;
} private static RedisClusterConfiguration getClusterConfiguration(RedisProperties properties) {
RedisProperties.Cluster cluster = properties.getCluster();
if (cluster != null) {
RedisClusterConfiguration config = new RedisClusterConfiguration(cluster.getNodes());
if (cluster.getMaxRedirects() != null) {
config.setMaxRedirects(cluster.getMaxRedirects());
}
return config;
}
return null;
} @Bean
@Autowired
public RedisTemplate<String, Object> redisTemplate(@Qualifier("RedisConnectionFactory") RedisConnectionFactory
connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory); //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper); template.setValueSerializer(serializer);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
} @Bean
public StringRedisTemplate stringRedisTemplate(
@Qualifier("RedisConnectionFactory") RedisConnectionFactory factory) {
StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
stringRedisTemplate.setConnectionFactory(factory);
return stringRedisTemplate;
} /**
* jedisCluster
*/
@Bean
@Autowired
public JedisCluster jedisCluster(@Qualifier("jedis.pool.config") JedisPoolConfig config,
@Value("${spring.redis.cluster.nodes}") String hostAndPort,
@Value("${spring.redis.password}") String password) {
/**
* 1 先检查redis集群是否已经配置
*/
if (StringUtils.isEmpty(hostAndPort)) {
throw new RuntimeException("Redis 集群初始化异常。请检查配置redis.host.address配置项");
} /**
* 2 根据配置构建hostAndPorts
*/
Set<HostAndPort> hostAndPorts = Arrays.asList(hostAndPort.split(",")).stream().map(s -> {
String[] split = s.split(":");
return new HostAndPort(split[0], Integer.valueOf(split[1]));
}).collect(Collectors.toSet()); return new JedisCluster(hostAndPorts, 1000, 1000, 1, password, config);
} @Bean(name = "jedis.pool.config")
public JedisPoolConfig jedisPoolConfig(@Value("${jedis.pool.config.maxTotal:100}") int maxTotal,
@Value("${jedis.pool.config.maxWaitMillis:5000}") int maxWaitMillis,
@Value("${jedis.pool.config.maxIdle:10}") int maxIdle) {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(maxTotal);
config.setMaxIdle(maxIdle);
config.setMaxWaitMillis(maxWaitMillis);
return config;
}
}
3.使用方式
@Autowired
private RedisTemplate<String,Object> redisTemplate;
// 操作String类型
redisTemplate.opsForValue().set("key","v1");
4.其他类型的获取
// hash结构
redisTemplate.opsForHash(); //set 结构
redisTemplate.opsForSet(); // sortedset
redisTemplate.opsForZSet(); //list
redisTemplate.opsForList();
5. key类的操作
public boolean existsKey(String key) {
return redisTemplate.hasKey(key);
} /**
* 删除key
*
* @param key
*/
public void deleteKey(String key) {
redisTemplate.delete(key);
} /**
* 设置key的生命周期
*
* @param key
* @param time
* @param timeUnit
*/
public void expireKey(String key, long time, TimeUnit timeUnit)
redisTemplate.expire(key, time, timeUnit);
}
根据配置RedisProperties自动获取RedisConnectionFactory的更多相关文章
- ARM-Linux配置DHCP自动获取IP地址
备注:内核版本:2.6.30.9busybox版本:1.15.2 PC Linux和开发板Linux的工作用户:root 1. 配置内核:[*] Networking support --->N ...
- Centos7(Linux)网络配置,自动获取ip地址
Centos7.0 Vmware 网络桥接配置,利用DHCP自动获取ip地址 首先要将Vmware10.0.3设置为桥接模式. CentOS 7.0默认安装好之后是没有自动开启网络连接的! cd / ...
- ubuntu 自动获取ip的怎么设置
ubuntu以DHCP方式配置网卡自动获取ip编辑文件/etc/network/interfaces:sudo vi /etc/network/interfaces并用下面的行来替换有关eth0的行: ...
- 转载-centos网络配置(手动设置,自动获取)的2种方法
转载地址:http://blog.51yip.com/linux/1120.html 重新启动网络配置 # service network restart 或 # /etc/init.d/networ ...
- centos网络配置方法(手动设置,自动获取)
不知道为什么最近一段时间网络特别的慢,还老是断,断的时候,局域网都连不上,当我手动设置一下ip后就可以了,搞得我很无语.下面是2种设置网络连接的方法,在说怎么设置前,一定要做好备份工作,特别是对于新手 ...
- centos网络配置(手动设置,自动获取)的2种方法3
不知道为什么最近一段时间网络特别的慢,还老是断,断的时候,局域网都连不上,当我手动设置一下ip后就可以了,搞得我很无语.下面是2种设置网络连接的方法,在说怎么设置前,一定要做好备份工作,特别是对于新手 ...
- CentOS 6.9使用Setup配置网络(解决dhcp模式插入网线不自动获取IP的问题)
说明:dhcp模式插入网线不自动获取IP是因为网卡没有激活,造成这种原因的,应该是安装系统时没有插入网线造成的. 解决方法: 修改网卡配置文件 vim /etc/sysconfig/network-s ...
- 关于启明星系统移除apppath配置,让系统自动获取路径来设置cookie的解决方法
启明星系统底层使用统一接口,特别是用户,用户登录后,都会建立一个 userinfo 的cookie.请看下面2个网址: http://120.24.86.232/book http://120.24. ...
- 配置idea中类头注释中的 ${user} 自动获取电脑的名字,怎么去修改名字
在idea安装路径下找到 idea\IntelliJ IDEA 2018.3.2\bin下面有一个文件叫:idea64.exe.vmoptions 编辑此文件就能修改主时钟自动获取的名称: 例如:添加 ...
随机推荐
- JSON.stringify常见用法
转摘于其他博客 var data =[ { name: "金",sex:"1",age:26 }, { name: "才",sex:&quo ...
- voc数据集坐标,coco数据集坐标
voc,如上图 x1 ,y1 ,x4, y4 bbox的坐标格式是,x,y的最大最小值,也就是box的左上角和右下角的坐标 coco x,y,w,h box左上角的坐标以及宽.高 图 ...
- Linux下安装Python,以及环境变量的配置
1.安装环境 centos7 + vmware + xshell 2.安装Python3 2.1下载Python资源包 网址:https://www.python.org/downloads/re ...
- java连接redis5.0单机版报连接超时错误
使用java代码测试redis5.0单机版时,报redis连接超时异常,而linux上的redis能正常访问: redis.clients.jedis.exceptions.JedisConnecti ...
- [NOIP2016][luogu]换教室[DP]
[NOIP2016] Day1 T3 换教室 ——!x^n+y^n=z^n 题目描述 对于刚上大学的牛牛来说,他面临的第一个问题是如何根据实际情况申请合适的课程. 在可以选择的课程中,有 2n 节课程 ...
- [UOJ211][UER #6]逃跑
题意:从原点出发,走\(n\)次,每次往四个方向中随机一个走,走每个方向有个概率,求所有方案走到过的点数的方差. 题解:orz kczno1 \(E*all=\sum (a_i-avg)^2*all= ...
- LintCode之最长单词
题目描述: 分析:先建一个数组s用来存储每个字符串的长度,然后遍历数组s得到最大的数max,这个数就是词典中的最长单词的长度,由于可能有多个长度相等的单词,所以要循环整个词典,当一个单词的长度等于ma ...
- Elasticsearch6.5安装&&常见问题与答案解释
ElasticSearch是一个用Java开发的基于Lucene的搜索服务器.它可以提供一个分布式多用户能力的全文搜索引擎,基于RESTfulweb接口.现阶段它主要为Apache许可条款下的开放源码 ...
- JQuery 字符串转时间格式
//字符串转时间格式 function getDate(strDate) { var date = eval('new Date(' + strDate.replace(/\d+(?=-[^-]+$) ...
- vue+element-ui国际化(i18n)
1. 下载element-ui和vue-i18n: npm i element-ui --save npm i vue-i18n –save 2. 创建一个 i18n 文件夹, 在main.j ...