微服務使用redis操作例項包含redis工具類
阿新 • • 發佈:2018-12-31
1、單機redis使用工具類
application.properties配置內容
#redis配置
#單機模式
#redis資料庫索引,預設為0
spring.redis.database=0
#redis伺服器地址
spring.redis.host=127.0.0.1
#redis伺服器連線埠號
spring.redis.port=6379
#redis伺服器連線密碼,預設為空
spring.redis.password=
#redis連線池最大活躍連線數
spring.redis.pool.max-active=8
#redis連線池最大阻塞等待時間
spring.redis. pool.max.wait=-1
#redis連線池最大空閒連線數
srping.redis.pool.max-idle=8
#redis連線池最小空閒連線數
spring.redis.pool.min-idle=0
#redis連線池超時時間,單位為毫秒
spring.redis.pool.timeout=60000
建立redis配置類RedisConfig
package com.sgcc.common;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation. CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
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.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
private String host = "127.0.0.1"; //redis伺服器IP
private int port = 6379; //redis伺服器埠
private int timeout = 60000; //redis超時時間設定
@Bean
public JedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(host);
factory.setPort(port);
factory.setTimeout(timeout); //設定連線超時時間
return factory;
}
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setDefaultExpiration(10); //設定key-value超時時間
return cacheManager;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
setSerializer(template); //設定序列化工具,這樣ReportBean不需要實現Serializable介面
template.afterPropertiesSet();
return template;
}
private void setSerializer(StringRedisTemplate template) {
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
}
}
建立redis工具類RedisUtil
package com.sgcc.common;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
@Component
@SuppressWarnings("all")
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
/**
* 寫入快取
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 寫入快取設定時效時間
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime, TimeUnit timeUnit) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, timeUnit);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 批量刪除對應的value
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量刪除key
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0) {
redisTemplate.delete(keys);
}
}
/**
* 刪除對應的value
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判斷快取中是否有對應的value
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 讀取快取
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 雜湊 新增
* @param key
* @param hashKey
* @param value
*/
public void hmSet(String key, Object hashKey, Object value) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key, hashKey, value);
}
/**
* 雜湊獲取資料
* @param key
* @param hashKey
* @return
*/
public Object hmGet(String key, Object hashKey) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key, hashKey);
}
/**
* 列表新增
* @param k
* @param v
*/
public void lPush(String k, Object v) {
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k, v);
}
/**
* 列表獲取
* @param k
* @param l
* @param l1
* @return
*/
public List<Object> lRange(String k, long l, long l1) {
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k, l, l1);
}
/**
* 集合新增
* @param key
* @param value
*/
public void add(String key, Object value) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key, value);
}
/**
* 集合獲取
* @param key
* @return
*/
public Set<Object> setMembers(String key) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}
/**
* 有序集合新增
* @param key
* @param value
* @param scoure
*/
public void zAdd(String key, Object value, double scoure) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key, value, scoure);
}
/**
* 有序集合獲取
* @param key
* @param scoure
* @param scoure1
* @return
*/
public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, scoure, scoure1);
}
/**
* 讀取字串快取
* @param key
* @return
*/
public String getString(String key) {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
String result = (String) operations.get(key);
return result;
}
/**
* 通過key刪除快取
* @param key
*/
public void deleteByKey(String key) {
remove(key);
}
/**
* 新增redis快取
* @param key
* @param value
* @return
*/
public void setString(String key, String value, int seconds) {
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 新增redis快取
* @param key
* @param value
* @return
*/
public void setString(String key, String value) {
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
} catch (Exception e) {
e.printStackTrace();
}
}
}
建立測試類test
package com.sgcc.common;
@Service
public class test {
@Autowired
private RedisUtil redis;
/**
* 刪除redis記錄
* @param codekey
* @return
*/
public void delRedisIdentCode(String codekey) {
redis.deleteByKey(codekey);
}
}
2、叢集redis使用工具類
application.properties配置內容
spring.redis.cluster.nodes=192.168.20.97:7000,192.168.20.97:7001,192.168.20.97:7002,192.168.20.98:7003,192.168.20.98:7004,192.168.20.98:7005
#最大重定向,由於叢集失敗機制是多數失敗則失敗,那麼叢集的最低標準是3個分片,1主1從,總共六個節點,
#所以如果當前節點失敗,最大的重定向為6-1=5,spring預設的也為5
spring.redis.cluster.max-redirects=5
#redis叢集響應超時時間
spring.redis.cluster.timeout=60000
建立工具類
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.BaseObjectPoolConfig;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.sgcc.tools.utils.SerilizableUtils;
import jodd.util.StringUtil;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Component
@SuppressWarnings("all")
public class RedisPool implements InitializingBean {
private final String[] redisGroupName = new String[]{"default"};
private final int DEFAULT_TIMEOUT = 6000;
private final int DEFAULT_MAXREDIRECTS = 5;
public Map<String, JedisCluster> jedisMap = new HashMap<String, JedisCluster>();
public JedisCluster jedis;
private final String defaultGroupName = "default";
private String nodes = "127.0.0.1:7000,30.20.110.52:7001,30.20.110.52:7002,127.0.0.1:7003,127.0.0.1:7004,127.0.0.1:7005";
private String maxRedirects = "5";
private String timeout = "60000";
private String password = "";
@Override
public void afterPropertiesSet() throws Exception {
try {
String[] ipPort = nodes.split(",");
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
// 控制一個pool最多有多少個狀態為idle(空閒的)的jedis例項。
config.setMaxIdle(20);
config.setMaxTotal(Integer.MAX_VALUE);
// 表示當borrow(引入)一個jedis例項時,最大的等待時間,如果超過等待時間,則直接丟擲JedisConnectionException;
config.setMaxWaitMillis(BaseObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS);
// 在獲取連線的時候檢查有效性, 預設false
config.setTestOnCreate(true);
config.setTestOnBorrow(true);
config.setTestOnReturn(true);
// 在空閒時檢查有效性, 預設false
config.setTestWhileIdle(true);
Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();
for(int j = 0 ; j < ipPort.length ; j++) {
String[] ipPortArr = ipPort[j].split(":");
jedisClusterNodes.add(new HostAndPort(ipPortArr[0], Integer.parseInt(ipPortArr[1])));
}
int t_timeout = StringUtils.isEmpty(timeout) ? DEFAULT_TIMEOUT: Integer.parseInt(timeout);
int t_maxRedirects = StringUtils.isEmpty(maxRedirects) ? DEFAULT_MAXREDIRECTS: Integer.parseInt(maxRedirects);
if(!StringUtil.