Redis集——SpringBoot连接Redis集(带密码)第⼀步,新建项⽬maven项⽬,添加依赖
(1)本⽂所采⽤的SpringBoot的版本如下
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
(2)加⼊Redis相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
第⼆步,l加⼊redis相关配置
springframework事务spring:
application:
name: redis-cluster
redis:
cluster:
nodes: 192.168.0.102:6379,192.168.0.103:6379,192.168.0.105:6379
max-redirects: 6
redis:
timeout: 10000 #客户端超时时间单位是毫秒默认是2000
maxIdle: 300 #最⼤空闲数
maxTotal: 1000 #控制⼀个pool可分配多少个jedis实例,⽤来替换上⾯的redis.maxActive,如果是jedis 2.4以后⽤该属性
maxWaitMillis: 1000 #最⼤建⽴连接等待时间。如果超过此时间将接到异常。设为-1表⽰⽆限制。
minEvictableIdleTimeMillis: 300000 #连接的最⼩空闲时间默认1800000毫秒(30分钟)
numTestsPerEvictionRun: 1024 #每次释放连接的最⼤数⽬,默认3
timeBetweenEvictionRunsMillis: 30000 #逐出扫描的时间间隔(毫秒) 如果为负数,则不运⾏逐出线程, 默认-1
testOnBorrow: true #是否在从池中取出连接前进⾏检验,如果检验失败,则从池中去除连接并尝试取出另⼀个
testWhileIdle: true #在空闲时检查有效性, 默认false
password: 123456 #密码
server:
port: 8080
第三步,编写配置类
package dis;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Value;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.tion.RedisClusterConfiguration;
import org.tion.RedisNode;
import org.tion.RedisPassword;
import org.tion.jedis.JedisConnectionFactory;
import org.RedisTemplate;
import org.dis.serializer.Jackson2JsonRedisSerializer;
import org.dis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
public class RedisClusterConfig {
@Value("${des}")
private String clusterNodes;
@Value("${dis.cluster.max-redirects}")
private int maxRedirects;
@Value("${redis.password}")
private String password;
@Value("${redis.timeout}")
private int timeout;
@Value("${redis.maxIdle}")
private int maxIdle;
@Value("${redis.maxTotal}")
private int maxTotal;
@Value("${redis.maxWaitMillis}")
private int maxWaitMillis;
@Value("${redis.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${redis.numTestsPerEvictionRun}")
private int numTestsPerEvictionRun;
@Value("${redis.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${stOnBorrow}")
private boolean testOnBorrow;
@Value("${stWhileIdle}")
private boolean testWhileIdle;
/**
* Redis连接池的配置
*
* @return JedisPoolConfig
*/
@Bean
public JedisPoolConfig getJedisPoolConfig() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
// 最⼤空闲数
jedisPoolConfig.setMaxIdle(maxIdle);
// 连接池的最⼤数据库连接数
jedisPoolConfig.setMaxTotal(maxTotal);
// 最⼤建⽴连接等待时间
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
// 逐出连接的最⼩空闲时间默认1800000毫秒(30分钟)
jedisPoolConfig.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
// 每次逐出检查时逐出的最⼤数⽬如果为负数就是 : 1/abs(n), 默认3
jedisPoolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
// 逐出扫描的时间间隔(毫秒) 如果为负数,则不运⾏逐出线程, 默认-1
jedisPoolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
// 是否在从池中取出连接前进⾏检验,如果检验失败,则从池中去除连接并尝试取出另⼀个
jedisPoolConfig.setTestOnBorrow(testOnBorrow);
// 在空闲时检查有效性, 默认false
jedisPoolConfig.setTestWhileIdle(testWhileIdle);
return jedisPoolConfig;
}
/
**
* Redis集的配置
*
* @return RedisClusterConfiguration
*/
@Bean
public RedisClusterConfiguration redisClusterConfiguration() {
RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
// Set<RedisNode> clusterNodes
String[] serverArray = clusterNodes.split(",");
Set<RedisNode> nodes = new HashSet<RedisNode>();
for (String ipPort : serverArray) {
String[] ipAndPort = ipPort.split(":");
nodes.add(new RedisNode(ipAndPort[0].trim(), Integer.valueOf(ipAndPort[1])));
}
redisClusterConfiguration.setClusterNodes(nodes);
redisClusterConfiguration.setMaxRedirects(maxRedirects);
redisClusterConfiguration.setPassword(RedisPassword.of(password));
return redisClusterConfiguration;
}
/**
* redis连接⼯⼚类
*
* @return JedisConnectionFactory
*/
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
// 集模式
JedisConnectionFactory factory = new JedisConnectionFactory(redisClusterConfiguration(), getJedisPoolConfig());
return factory;
}
/**
* 实例化 RedisTemplate 对象
*
* @return RedisTemplate<String, Object>
*/
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
// Template初始化
initDomainRedisTemplate(redisTemplate);
return redisTemplate;
}
/**
* 设置数据存⼊ redis 的序列化⽅式使⽤默认的序列化会导致key乱码
*/
private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
// 开启redis数据库事务的⽀持
redisTemplate.setEnableTransactionSupport(true);
redisTemplate.setConnectionFactory(jedisConnectionFactory());
// 如果不配置Serializer,那么存储的时候缺省使⽤String,如果⽤User类型存储,那么会提⽰错误User can't cast to // String!
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
// hash的key也采⽤String的序列化⽅式
redisTemplate.setHashKeySerializer(stringRedisSerializer);
// jackson序列化对象设置
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(
Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
jackson2JsonRedisSerializer.setObjectMapper(om);
// value序列化⽅式采⽤jackson
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化⽅式采⽤jackson
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
}
}
第四步,编写Controller测试类
package com.qxj.application;
import org.springframework.beans.factory.annotation.Autowired;
import org.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Autowired
private RedisTemplate<String, Object> template;
@RequestMapping("/test")
public String test() {
template.opsForValue().set("demo", "hello world! 你好,世界");
String str = (String) template.opsForValue().get("demo");
return str;
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论