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";
private int port = 6379;
private int timeout = 60000;
@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);
return cacheManager;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
setSerializer(template);
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;
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;
}
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;
}
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0) {
redisTemplate.delete(keys);
}
}
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
public void hmSet(String key, Object hashKey, Object value) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key, hashKey, value);
}
public Object hmGet(String key, Object hashKey) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key, hashKey);
}
public void lPush(String k, Object v) {
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k, v);
}
public List<Object> lRange(String k, long l, long l1) {
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k, l, l1);
}
public void add(String key, Object value) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key, value);
}
public Set<Object> setMembers(String key) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}
public void zAdd(String key, Object value, double scoure) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key, value, scoure);
}
public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, scoure, scoure1);
}
public String getString(String key) {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
String result = (String) operations.get(key);
return result;
}
public void deleteByKey(String key) {
remove(key);
}
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();
}
}
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;
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();
config.setMaxIdle(20);
config.setMaxTotal(Integer.MAX_VALUE);
config.setMaxWaitMillis(BaseObjectPoolConfig.DEFAULT_MAX_WAIT_MILLIS);
config.setTestOnCreate(true);
config.setTestOnBorrow(true);
config.setTestOnReturn(true);
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.isEmpty(password)){
jedisMap.put(redisGroupName[0], new JedisCluster(jedisClusterNodes, t_timeout,
t_timeout, t_maxRedirects, password, config));
}else{
jedisMap.put(redisGroupName[0], new JedisCluster(jedisClusterNodes, t_timeout,
t_timeout, t_maxRedirects, config));
}
jedis = jedisMap.get(defaultGroupName);
} catch(Exception e){
e.printStackTrace();
}
}
public Long getQueueCount(String groupName, String key) {
Long count = jedisMap.get(groupName).llen(key);
return count;
}
public Long getQueueCount(String key) {
return getQueueCount(defaultGroupName, key);
}
public String getFromQueueFirst(String groupName, String key) {
String lpop = jedisMap.get(groupName).lpop(key);
return lpop;
}
public String getFromQueueFirst(String key) {
return getFromQueueFirst(defaultGroupName, key);
}
public String getFromQueueLast(String groupName, String key) {
String rpop = jedisMap.get(groupName).rpop(key);
return rpop;
}
public String getFromQueueLast(String key) {
return getFromQueueLast(defaultGroupName, key);
}
public String blockQueueLast(String groupName, String key) {
List<String> rpop = jedisMap.get(groupName).brpop(10, key);
if (rpop == null || rpop.size() < 1) return null;
return rpop.get(1);
}
public String blockQueueLast(String key) {
return blockQueueLast(defaultGroupName, key);
}
public void setObject(String groupName, String key, Object obj) {
jedisMap.get(groupName).set(key.getBytes(), SerilizableUtils.serialize(obj));
}
public void setObject(String key, Object obj) {
setObject(defaultGroupName, key, obj);
}
public Object getObject(String groupName, String key) {
byte[] bs = jedisMap.get(groupName).get(key.getBytes());
return SerilizableUtils.unserialize(bs);
}
public Object getObject(String key) {
return getObject(defaultGroupName, key);
}
public void setString(String groupName, String key, String value) {
jedisMap.get(groupName).set(key, value);
}
public void setString(String key, String value) {
setString(defaultGroupName, key, value);
}
public void setString(String groupName, String key, String value, int seconds) {
jedisMap.get(groupName).setex(key, seconds, value);
}
public void setString(String key, String value, int seconds) {
setString(defaultGroupName, key, value, seconds);
}
public String getString(String groupName, String key) {
String value = jedisMap.get(groupName).get(key);
return value;
}
public String getString(String key) {
return getString(defaultGroupName, key);
}
public void setMap(String groupName, String key, Map<String, String> map) {
jedisMap.get(groupName).hmset(key, map);
}
public void setMap(String key, Map<String, String> map) {
setMap(defaultGroupName, key, map);
}
public Map<String, String> getMap(String groupName, String key) {
Map<String, String> hgetAll = jedisMap.get(groupName).hgetAll(key);
return hgetAll;
}
public Map<String, String> getMap(String key) {
return getMap(defaultGroupName, key);
}
public void setMap(String groupName, byte[] key, Map<byte[], byte[]> map) {
jedisMap.get(groupName).hmset(key, map);
}
public void setMap(byte[] key, Map<byte[], byte[]> map) {
setMap(defaultGroupName, key, map);
}
public void setMap(String groupName, byte[] key, Map<byte[], byte[]> map, int seconds) {
jedisMap.get(groupName).hmset(key, map);
jedisMap.get(groupName).expire(key, seconds);
}
public void setMap(byte[] key, Map<byte[], byte[]> map, int seconds) {
setMap(defaultGroupName, key, map, seconds);
}
public Map<byte[], byte[]> getMap(String groupName, byte[] key) {
Map<byte[], byte[]> hgetAll = jedisMap.get(groupName).hgetAll(key);
return hgetAll;
}
public Map<byte[], byte[]> getMap(byte[] key) {
return getMap(defaultGroupName, key);
}
public Set<String> getKeys(String groupName, String pattern) {
Set<String> keys = new HashSet<String>();
Map<String, JedisPool> clusterNodes = jedisMap.get(groupName).getClusterNodes();
String[] split = nodes.split(",");
for (String string : split) {
JedisPool jedisPool = clusterNodes.get(string);
Jedis resource = jedisPool.getResource();
keys.addAll(resource.keys(pattern));
resource.close();
}
return keys;
}
public Set<String> getKeys(String pattern) {
return getKeys(defaultGroupName, pattern);
}
public List<String> getStringListByKeyLike(String groupName, String pattern) {
Set<String> keys = getKeys(groupName, pattern);
List<String> stringList = new ArrayList<String>();
Iterator<String> iterator = keys.iterator();
while (iterator.hasNext()) {
String key = iterator.next();
stringList.add(getString(groupName, key));
}
return stringList;
}
public List<String> getStringListByKeyLike(String pattern) {
return getStringListByKeyLike(defaultGroupName, pattern);
}
public ArrayList getValues(String groupName, String[] key) {
ArrayList arrayList = new ArrayList();
for (int i = 0; i < key.length; i++) {
String redisValue = jedisMap.get(groupName).get(key[i]);
arrayList.add(i, redisValue);
}
return arrayList;
}
public ArrayList getValues(String[] key) {
return getValues(defaultGroupName, key);
}
public List<Map<String, String>> getListByKeyLike(String groupName, String pattern) {
Set<String> keys = getKeys(groupName, pattern);
List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
Iterator<String> iterator = keys.iterator();
while (iterator.hasNext()) {
String key = iterator.next();
mapList.add(getMap(groupName, key));
}
return mapList;
}
public List<Map<String, String>> getListByKeyLike(String pattern) {
return getListByKeyLike(defaultGroupName, pattern);
}
public Map<String, String> getMapByKeyLike(String groupName, String pattern) {
Set<String> keys = getKeys(groupName, pattern);
Map<String, String> mapList = new HashMap<String, String>();
Iterator<String> iterator = keys.iterator();
while (iterator.hasNext()) {
String key = iterator.next();
mapList.put(key, getString(groupName, key));
}
return mapList;
}
public Map<String, String> getMapByKeyLike(String pattern) {
return getMapByKeyLike(defaultGroupName, pattern);
}
public Map<String, String> getTreeMapByKeyLike(String groupName, String pattern) {
Set<String> keys = getKeys(groupName, pattern);
Map<String, String> mapList = new TreeMap<String, String>();
Iterator<String> iterator = keys.iterator();
while (iterator.hasNext()) {
String key = iterator.next();
mapList.put(key, getString(groupName, key));
}
return mapList;
}
public Map<String, String> getTreeMapByKeyLike(String pattern) {
return getTreeMapByKeyLike(defaultGroupName, pattern);
}
public String getListSizeByKeyLike(String groupName, String pattern) {
Set<String> keys = getKeys(groupName, pattern);
return String.valueOf(keys.size());
}
public String getListSizeByKeyLike(String pattern) {
return getListSizeByKeyLike(defaultGroupName, pattern);
}
public Set<String> getKeysByKeyLike(String groupName, String pattern) {
Set<String> keys = getKeys(groupName, pattern);
return keys;
}
public Set<String> getKeysByKeyLike(String pattern) {
return getKeysByKeyLike(defaultGroupName, pattern);
}
public void delByKeyLike(String groupName, String pattern) {
Set<String> keys = getKeys(groupName, pattern);
for(String key : keys)
jedisMap.get(groupName).del(key);
}
public void delByKeyLike(String pattern) {
delByKeyLike(defaultGroupName, pattern);
}
public void setValueSet(String groupName, String key, String field, String value) {
jedisMap.get(groupName).hset(key, field, value);
}
public void setValueSet(String key, String field, String value) {
setValueSet(defaultGroupName, key, field, value);
}
public void deleteByKey(String groupName, String key) {
jedisMap.get(groupName).del(key);
}
public void deleteByKey(String key) {
deleteByKey(defaultGroupName, key);
}
public Map<String, String> getValueSet(String groupName, String key) {
ArrayList<Object> arrayList = new ArrayList<Object>();
Map<String, String> hgetAll = jedisMap.get(groupName).hgetAll(key);
return hgetAll;
}
public Map<String, String> getValueSet(String key) {
return getValueSet(defaultGroupName, key);
}
public String getValueFromMap(String groupName, String key, String field) {
String value = jedisMap.get(groupName).hget(key, field);
return value;
}
public String getValueFromMap(String key, String field) {
return getValueFromMap(defaultGroupName, key, field);
}
}