第一种
springBoot2.0以后版本做了重大更新,本博客基于的是1.5.10版本,不适用于2.0以上的版本,
然后是redis的配置文件:
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
/**
- ClassName: JedisClusterConfig
- Description:
- @date 2018年4月3日
*/
@Configuration
public class JedisClusterConfig {
private static final Logger log = LoggerFactory.getLogger(JedisClusterConfig.class);
@Value("${redis.nodes}")
private String nodes;
@Value("${redis.commandTimeout}")
private int commandTimeout;
@Value("${redis.pwd}")
private String pwd;
@Value("${redis.maxTotal}")
private int maxTotal;
@Value("${redis.maxIdle}")
private int maxIdle;
@Value("${redis.minIdle}")
private int minIdle;
@Value("${redis.maxWait}")
private int maxWait;
/**
- 注意:
- 这里返回的JedisCluster是单例的,并且可以直接注入到其他类中去使用
- @return
*/
@Bean
public JedisCluster getJedisCluster() {
log.info(“进入redis集群初始化方法:访问集群地址为:”+nodes);
String[] serverArray = nodes.split(",");//获取服务器数组(这里要相信自己的输入,所以没有考虑空指针问题)
Set nodes = new HashSet<>();
for (String ipPort : serverArray) {
String[] ipPortPair = ipPort.split("😊;
nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
}
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(maxTotal);
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);//设置最小空闲数
config.setMaxWaitMillis(maxWait);
//在获取Jedis连接时,自动检验连接是否可用
config.setTestOnBorrow(true);
//在将连接放回池中前,自动检验连接是否有效
config.setTestOnReturn(true);
//自动测试池中的空闲连接是否都是可用连接
config.setTestWhileIdle(true);
//连接耗尽时是否阻塞, false报异常,ture阻塞直到超时,默认true
config.setBlockWhenExhausted(false);
//表示idle object evitor两次扫描之间要sleep的毫秒数
config.setTimeBetweenEvictionRunsMillis(30000);
//表示idle object evitor每次扫描的最多的对象数
config.setNumTestsPerEvictionRun(10);
//表示一个对象至少停留在idle状态的最短时间,然后才能被idle object evitor扫描并驱逐;这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义
config.setMinEvictableIdleTimeMillis(60000);
//需要密码连接的创建对象方式
//参数依次是:集群地址,链接超时时间,返回值的超时时间,链接尝试次数,密码和配置文件
return new JedisCluster(nodes,commandTimeout,10000,3,pwd,config);
}
}
这里提供的是最全的JedisCluster实例化方法,
public JedisCluster(HostAndPort node) {
this(Collections.singleton(node), DEFAULT_TIMEOUT);
}
public JedisCluster(HostAndPort node, int timeout) {
this(Collections.singleton(node), timeout, DEFAULT_MAX_REDIRECTIONS);
}
public JedisCluster(HostAndPort node, int timeout, int maxAttempts) {
this(Collections.singleton(node), timeout, maxAttempts, new GenericObjectPoolConfig());
}
public JedisCluster(HostAndPort node, final GenericObjectPoolConfig poolConfig) {
this(Collections.singleton(node), DEFAULT_TIMEOUT, DEFAULT_MAX_REDIRECTIONS, poolConfig);
}
public JedisCluster(HostAndPort node, int timeout, final GenericObjectPoolConfig poolConfig) {
this(Collections.singleton(node), timeout, DEFAULT_MAX_REDIRECTIONS, poolConfig);
}
public JedisCluster(HostAndPort node, int timeout, int maxAttempts,
final GenericObjectPoolConfig poolConfig) {
this(Collections.singleton(node), timeout, maxAttempts, poolConfig);
}
public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout,
int maxAttempts, final GenericObjectPoolConfig poolConfig) {
super(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, poolConfig);
}
public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout,
int maxAttempts, String password, final GenericObjectPoolConfig poolConfig) {
super(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, password, poolConfig);
}
public JedisCluster(Set nodes) {
this(nodes, DEFAULT_TIMEOUT);
}
public JedisCluster(Set nodes, int timeout) {
this(nodes, timeout, DEFAULT_MAX_REDIRECTIONS);
}
public JedisCluster(Set nodes, int timeout, int maxAttempts) {
this(nodes, timeout, maxAttempts, new GenericObjectPoolConfig());
}
public JedisCluster(Set nodes, final GenericObjectPoolConfig poolConfig) {
this(nodes, DEFAULT_TIMEOUT, DEFAULT_MAX_REDIRECTIONS, poolConfig);
}
public JedisCluster(Set nodes, int timeout, final GenericObjectPoolConfig poolConfig) {
this(nodes, timeout, DEFAULT_MAX_REDIRECTIONS, poolConfig);
}
public JedisCluster(Set jedisClusterNode, int timeout, int maxAttempts,
final GenericObjectPoolConfig poolConfig) {
super(jedisClusterNode, timeout, maxAttempts, poolConfig);
}
public JedisCluster(Set jedisClusterNode, int connectionTimeout, int soTimeout,
int maxAttempts, final GenericObjectPoolConfig poolConfig) {
super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, poolConfig);
}
public JedisCluster(Set jedisClusterNode, int connectionTimeout, int soTimeout,
int maxAttempts, String password, final GenericObjectPoolConfig poolConfig) {
super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, password, poolConfig);
}
@Value("${redis.maxIdle}")注入,也可用@ConfigurationProperties直接将参数
redis:
nodes: 10.200.200.2:7011,10.200.200.2:7012,10.200.200.2:7013,10.200.200.2:7014,10.200.200.2:7015,10.200.200.2:7016
commandTimeout: 10000 #redis操作的超时时间
maxTotal: 5000 #最大连接数
maxIdle: 30 #最大空闲连接数
minIdle: 5 #最小空闲连接数
maxWait: 3000 #获取连接最大等待时间 ms #default -1
pwd:
/**
- ClassName: RedisUtil
- Description:
- @date 2018年4月3日
*/
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;
@Component
public class RedisUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(RedisUtil.class);
@Autowired
private JedisCluster jedisCluster;
/**
- 设置缓存
- @param key 缓存key
- @param value 缓存value
*/
public void set(String key, String value) {
jedisCluster.set(key, value);
LOGGER.debug(“RedisUtil:set cache key={},value={}”, key, value);
}
/**
- 设置缓存对象
- @param key 缓存key
- @param obj 缓存value
*/
public void setObject(String key, T obj , int expireTime) {
jedisCluster.setex(key, expireTime, JSON.toJSONString(obj));
}
/**
- 获取指定key的缓存
- @param key—JSON.parseObject(value, User.class);
*/
public String getObject(String key) {
return jedisCluster.get(key);
}
/**
- 判断当前key值 是否存在
- @param key
*/
public boolean hasKey(String key) {
return jedisCluster.exists(key);
}
/**
- 设置缓存,并且自己指定过期时间
- @param key
- @param value
- @param expireTime 过期时间
*/
public void setWithExpireTime( String key, String value, int expireTime) {
jedisCluster.setex(key, expireTime, value);
LOGGER.debug(“RedisUtil:setWithExpireTime cache key={},value={},expireTime={}”, key, value, expireTime);
}
/**
- 获取指定key的缓存
- @param key
*/
public String get(String key) {
String value = jedisCluster.get(key);
LOGGER.debug(“RedisUtil:get cache key={},value={}”,key, value);
return value;
}
/**
- 删除指定key的缓存
- @param key
*/
public void delete(String from,String key) {
jedisCluster.del(key);
LOGGER.info(“RedisUtil:delete “+from+” cache key={}”, key);
}
/**
- @Title: expire
- @Description: 更新key的失效时间
- @param key
- @throws
*/
public Long expire(String key,int seconds) {
LOGGER.debug(“RedisUtil:expire cache key={}”, key);
return jedisCluster.expire(key, seconds);
}
public Long pexpire(String key,long seconds) {
LOGGER.debug(“RedisUtil:expire cache key={}”, key);
return jedisCluster.pexpire(key, seconds);
}
}
第二种
第一步:添加redis依赖;
redis.clients
jedis
第二步:yml配置文件信息添加
spring:
redis:
cluster:
#设置key的生存时间,当key过期时,它会被自动删除;
expire-seconds: 120
#设置命令的执行时间,如果超过这个时间,则报错;
command-timeout: 5000
#设置redis集群的节点信息,其中namenode为域名解析,通过解析域名来获取相应的地址;
nodes: namenode22:6379,datanode23:6379,datanode24:6379,datanode25:6379,datanode26:6379,datanode27:6379
第三步:编写相关java代码;
1)、读取application.yml配置文件中的属性信息到bean中,并注入到spring容器;
package com.example.springbootdemoconsumer.redisConfig;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
*/
//依赖注入
@Component
//该注解用于读取配置文件中的属性,其中prefix表示前缀;
@ConfigurationProperties(prefix = “spring.redis.cluster”)
public class RedisProperties {
private int expireSeconds;
private String nodes;
private int commandTimeout;
public int getExpireSeconds() {
return expireSeconds;
}
public void setExpireSeconds(int expireSeconds) {
this.expireSeconds = expireSeconds;
}
public String getNodes() {
return nodes;
}
public void setNodes(String nodes) {
this.nodes = nodes;
}
public int getCommandTimeout() {
return commandTimeout;
}
public void setCommandTimeout(int commandTimeout) {
this.commandTimeout = commandTimeout;
}
@Override
public String toString() {
return "RedisProperties{" +
"expireSeconds=" + expireSeconds +
", nodes='" + nodes + '\'' +
", commandTimeout=" + commandTimeout +
'}';
}
}
2)、根据注入的RedisProperties对象来获取JedisCluster对象;
package com.example.springbootdemoconsumer.redisConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import java.util.HashSet;
import java.util.Set;
/**
*
*/
@Configuration
public class RedisConfig {
@Autowired
private RedisProperties redisProperties;
@Bean
public JedisCluster getJedisCluster(){
//获取redis集群的ip及端口号等相关信息;
String[] serverArray = redisProperties.getNodes().split(",");
Set<HostAndPort> nodes = new HashSet<>();
//遍历add到HostAndPort中;
for (String ipPort : serverArray) {
String[] ipPortPair = ipPort.split(":");
nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
}
//构建对象并返回;
return new JedisCluster(nodes, redisProperties.getCommandTimeout());
}
}
3)、创建一个操作redis集群的接口,并对该接口进行实现,实现类中写了对redis操作的主要的方法;
package com.example.springbootdemoconsumer.redisConfig;
/**
*
*/
public interface JedisClient {
String set(String key, String value);
String get(String key);
Boolean exists(String key);
Long expire(String key, int seconds);
Long ttl(String key);
Long incr(String key);
Long hset(String key, String field, String value);
String hget(String key, String field);
Long hdel(String key, String... field);
}
实现类如下:
package com.example.springbootdemoconsumer.service;
import com.example.springbootdemoconsumer.redisConfig.JedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;
/**
*
*/
@Component
public class JedisClientCluster implements JedisClient {
@Autowired
private JedisCluster jedisCluster;
@Override
public String set(String key, String value) {
return jedisCluster.set(key, value);
}
@Override
public String get(String key) {
return jedisCluster.get(key);
}
@Override
public Boolean exists(String key) {
return jedisCluster.exists(key);
}
@Override
public Long expire(String key, int seconds) {
return jedisCluster.expire(key, seconds);
}
@Override
public Long ttl(String key) {
return jedisCluster.ttl(key);
}
@Override
public Long incr(String key) {
return jedisCluster.incr(key);
}
@Override
public Long hset(String key, String field, String value) {
return jedisCluster.hset(key, field, value);
}
@Override
public String hget(String key, String field) {
return jedisCluster.hget(key, field);
}
@Override
public Long hdel(String key, String... field) {
return jedisCluster.hdel(key, field);
}
}
4):编写Controller,进行测试;
package com.example.springbootdemoconsumer.controller;
import com.example.springbootdemoconsumer.redisConfig.RedisConfig;
import com.example.springbootdemoconsumer.redisConfig.RedisProperties;
import com.example.springbootdemoconsumer.service.JedisClientCluster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
*
*/
@RestController
public class RedisController {
@Autowired
private RedisProperties redisProperties;
@Autowired
private RedisConfig redisConfig;
@Autowired
private JedisClientCluster jedisClientCluster;
@RequestMapping(value = "getRedisValue")
public String getRedisValue(){
System.out.println(redisProperties.toString());
System.out.println(redisConfig.getJedisCluster().getClusterNodes());
System.out.println(jedisClientCluster.get("yp"));
jedisClientCluster.set("12","12");
System.out.println(jedisClientCluster.get("12"));
return jedisClientCluster.get("12");
}
}