博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring与spring-data-redis整合redis
阅读量:6157 次
发布时间:2019-06-21

本文共 14456 字,大约阅读时间需要 48 分钟。

 

classpath:redis.properties

 

spring-context-jedis-cluster.xml

Jedis Cluster Configuration集群

 

redis-cluster.properties#cluster configurationredis.host1=xx.xx.xx.xxredis.port1=7000redis.host2=xx.xx.xx.xxredis.port2=7001redis.host3=xx.xx.xx.xxredis.port3=7002redis.host4=xx.xx.xx.xxredis.port4=7000redis.host5=xx.xx.xx.xxredis.port5=7001redis.host6=xx.xx.xx.xxredis.port6=7002redis.maxRedirects=3redis.maxIdle=100redis.maxTotal=600

 

 

package cn.zsmy.palmdoctor.redis;import java.io.Serializable;import java.util.ArrayList;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.TimeUnit;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.dao.DataAccessException;import org.springframework.data.redis.connection.RedisConnection;import org.springframework.data.redis.core.BoundSetOperations;import org.springframework.data.redis.core.HashOperations;import org.springframework.data.redis.core.ListOperations;import org.springframework.data.redis.core.RedisCallback;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Service;@Servicepublic class RedisUtil{    @Autowired     @Qualifier("redisTemplate")    public RedisTemplate
redisTemplate; @Autowired @Qualifier("redisTemplate") protected RedisTemplate
redisTemplateSerializable; /** * 缓存基本的对象,Integer、String、实体类等 * @param key 缓存的键值 * @param value 缓存的值 * @return 缓存的对象 */ public void setCacheObject(String key, Object value) { redisTemplate.opsForValue().set(key,value); } /** * 获得缓存的基本对象。 * @param key 缓存键值 * @param operation * @return 缓存键值对应的数据 */ public Object getCacheObject(String key/*,ValueOperations
operation*/) { return redisTemplate.opsForValue().get(key); } /** * 缓存List数据 * @param key 缓存的键值 * @param dataList 待缓存的List数据 * @return 缓存的对象 */ public Object setCacheList(String key, List
dataList) { ListOperations
listOperation = redisTemplate.opsForList(); if(null != dataList) { int size = dataList.size(); for(int i = 0; i < size ; i ++) { listOperation.rightPush(key,dataList.get(i)); } } return listOperation; } /** * 获得缓存的list对象 * @param key 缓存的键值 * @return 缓存键值对应的数据 */ public List
getCacheList(String key) { List dataList = new ArrayList(); ListOperations
listOperation = redisTemplate.opsForList(); Long size = listOperation.size(key); for(int i = 0 ; i < size ; i ++) { dataList.add(listOperation.leftPop(key)); } return dataList; } /** * 获得缓存的list对象 * @Title: range * @Description: TODO(这里用一句话描述这个方法的作用) * @param @param key * @param @param start * @param @param end * @param @return * @return List
返回类型 * @throws */ public List
range(String key, long start, long end) { ListOperations
listOperation = redisTemplate.opsForList(); return listOperation.range(key, start, end); } /** * list集合长度 * @param key * @return */ public Long listSize(String key) { return redisTemplate.opsForList().size(key); } /** * 覆盖操作,将覆盖List中指定位置的值 * @param key * @param int index 位置 * @param String * value 值 * @return 状态码 * */ public void listSet(String key, int index, Object obj) { redisTemplate.opsForList().set(key, index, obj); } /** * 向List尾部追加记录 * * @param String * key * @param String * value * @return 记录总数 * */ public long leftPush(String key, Object obj) { return redisTemplate.opsForList().leftPush(key, obj); } /** * 向List头部追加记录 * * @param String * key * @param String * value * @return 记录总数 * */ public long rightPush(String key, Object obj) { return redisTemplate.opsForList().rightPush(key, obj); } /** * 算是删除吧,只保留start与end之间的记录 * * @param String * key * @param int start 记录的开始位置(0表示第一条记录) * @param int end 记录的结束位置(如果为-1则表示最后一个,-2,-3以此类推) * @return 执行状态码 * */ public void trim(String key, int start, int end) { redisTemplate.opsForList().trim(key, start, end); } /** * 删除List中c条记录,被删除的记录值为value * * @param String * key * @param int c 要删除的数量,如果为负数则从List的尾部检查并删除符合的记录 * @param Object * obj 要匹配的值 * @return 删除后的List中的记录数 * */ public long remove(String key, long i, Object obj) { return redisTemplate.opsForList().remove(key, i, obj); } /** * 缓存Set * @param key 缓存键值 * @param dataSet 缓存的数据 * @return 缓存数据的对象 */ public BoundSetOperations
setCacheSet(String key,Set
dataSet) { BoundSetOperations
setOperation = redisTemplate.boundSetOps(key); /*T[] t = (T[]) dataSet.toArray(); setOperation.add(t);*/ Iterator
it = dataSet.iterator(); while(it.hasNext()) { setOperation.add(it.next()); } return setOperation; } /** * 获得缓存的set * @param key * @param operation * @return */ public Set getCacheSet(String key/*,BoundSetOperations
operation*/) { Set
dataSet = new HashSet(); BoundSetOperations
operation = redisTemplate.boundSetOps(key); Long size = operation.size(); for(int i = 0 ; i < size ; i++) { dataSet.add(operation.pop()); } return dataSet; } /** * 缓存Map * @param key * @param dataMap * @return */ public int setCacheMap(String key,Map
dataMap) { if(null != dataMap) { HashOperations
hashOperations = redisTemplate.opsForHash(); for (Map.Entry
entry : dataMap.entrySet()) { /*System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); */ if(hashOperations != null){ hashOperations.put(key,entry.getKey(),entry.getValue()); } else{ return 0; } } } else{ return 0; } return dataMap.size(); } /** * 获得缓存的Map * @param key * @param hashOperation * @return */ public Map
getCacheMap(String key/*,HashOperations
hashOperation*/) { Map
map = redisTemplate.opsForHash().entries(key); /*Map
map = hashOperation.entries(key);*/ return map; } /** * 缓存Map * @param key * @param dataMap * @return */ public void setCacheIntegerMap(String key,Map
dataMap) { HashOperations
hashOperations = redisTemplate.opsForHash(); if(null != dataMap) { for (Map.Entry
entry : dataMap.entrySet()) { /*System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); */ hashOperations.put(key,entry.getKey(),entry.getValue()); } } } /** * 获得缓存的Map * @param key * @param hashOperation * @return */ public Map
getCacheIntegerMap(String key/*,HashOperations
hashOperation*/) { Map
map = redisTemplate.opsForHash().entries(key); /*Map
map = hashOperation.entries(key);*/ return map; } /** * 从hash中删除指定的存储 * * @param String * @return 状态码,1成功,0失败 * */ public long deleteMap(String key) { redisTemplate.setEnableTransactionSupport(true); return redisTemplate.opsForHash().delete(key); } /** * 设置过期时间 * @param key * @param time * @param unit * @return */ public boolean expire(String key, long time, TimeUnit unit) { return redisTemplate.expire(key, time, unit); } /** * increment * @param key * @param step * @return */ public long increment(String key, long step) { return redisTemplate.opsForValue().increment(key, step); } //redisTemplateSerializable /** * 删除redis的所有数据 */ /*@SuppressWarnings({"unchecked", "rawtypes"}) public String flushDB() { return redisTemplateSerializable.execute(new RedisCallback() { public String doInRedis(RedisConnection connection) throws DataAccessException { connection.flushDb(); return "ok"; } }); }*/ public long del(final byte[] key) { return (long) redisTemplateSerializable.execute(new RedisCallback
() { public Long doInRedis(RedisConnection connection) { return connection.del(key); } }); } @SuppressWarnings({ "unchecked", "rawtypes"}) public byte[] get(final byte[] key) { return (byte[]) redisTemplateSerializable.execute(new RedisCallback() { public byte[] doInRedis(RedisConnection connection) throws DataAccessException { return connection.get(key); } }); } /** * @param key * @param value * @param liveTime */ public void set(final byte[] key, final byte[] value, final long liveTime) { redisTemplateSerializable.execute(new RedisCallback() { public Long doInRedis(RedisConnection connection) throws DataAccessException { connection.set(key, value); if (liveTime > 0) { connection.expire(key, liveTime); } return 1L; } }); }}

 

 

package cn.zsmy.palmdoctor.redis;import java.util.HashSet;import java.util.Properties;import java.util.Set;import java.util.regex.Pattern;import org.apache.commons.pool2.impl.GenericObjectPoolConfig;import org.springframework.beans.factory.FactoryBean;import org.springframework.beans.factory.InitializingBean;import org.springframework.core.io.Resource;import redis.clients.jedis.HostAndPort;import redis.clients.jedis.JedisCluster;public class JedisClusterFactory implements FactoryBean
, InitializingBean { private Resource addressConfig; private String addressKeyPrefix ; private String password; private JedisCluster jedisCluster; private Integer timeout; private Integer maxRedirections; private GenericObjectPoolConfig genericObjectPoolConfig; private Pattern p = Pattern.compile("^.+[:]\\d{1,5}\\s*$"); @Override public JedisCluster getObject() throws Exception { return jedisCluster; } @Override public Class
getObjectType() { return (this.jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class); } @Override public boolean isSingleton() { return true; } private Set
parseHostAndPort() throws Exception { try { Properties prop = new Properties(); prop.load(this.addressConfig.getInputStream()); Set
haps = new HashSet
(); for (Object key : prop.keySet()) { if (!((String) key).startsWith(addressKeyPrefix)) { continue; } String val = (String) prop.get(key); boolean isIpPort = p.matcher(val).matches(); if (!isIpPort) { throw new IllegalArgumentException("ip 或 port 不合法"); } String[] ipAndPort = val.split(":"); HostAndPort hap = new HostAndPort(ipAndPort[0], Integer.parseInt(ipAndPort[1])); haps.add(hap); } return haps; } catch (IllegalArgumentException ex) { throw ex; } catch (Exception ex) { throw new Exception("解析 jedis 配置文件失败", ex); } } @Override public void afterPropertiesSet() throws Exception { Set
haps = this.parseHostAndPort(); //jedisCluster = new JedisCluster(haps, timeout, maxRedirections,genericObjectPoolConfig); jedisCluster = new JedisCluster(haps, timeout, 2000, maxRedirections, password, genericObjectPoolConfig); } public void setAddressConfig(Resource addressConfig) { this.addressConfig = addressConfig; } public void setTimeout(int timeout) { this.timeout = timeout; } public void setMaxRedirections(int maxRedirections) { this.maxRedirections = maxRedirections; } public void setAddressKeyPrefix(String addressKeyPrefix) { this.addressKeyPrefix = addressKeyPrefix; } public void setGenericObjectPoolConfig(GenericObjectPoolConfig genericObjectPoolConfig) { this.genericObjectPoolConfig = genericObjectPoolConfig; } public void setPassword(String password) { this.password = password; }}

 

package cn.zsmy.palmdoctor.redis;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.Closeable;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import cn.zsmy.constant.Constant;/** * @author shm */public class SerializeUtil {    public static byte[] serialize(Object value) {        if (value == null) {            throw new NullPointerException("Can't serialize null");        }        byte[] rv = null;        ByteArrayOutputStream bos = null;        ObjectOutputStream os = null;        try {            bos = new ByteArrayOutputStream();            os = new ObjectOutputStream(bos);            os.writeObject(value);            os.close();            bos.close();            rv = bos.toByteArray();        } catch (Exception e) {            e.printStackTrace();            Constant.MY_LOG.info("serialize error");        } finally {            close(os);            close(bos);        }        return rv;    }    public static Object deserialize(byte[] in) {        return deserialize(in, Object.class);    }    @SuppressWarnings("unchecked")    public static 
T deserialize(byte[] in, Class
requiredType) { Object rv = null; ByteArrayInputStream bis = null; ObjectInputStream is = null; try { if (in != null) { bis = new ByteArrayInputStream(in); is = new ObjectInputStream(bis); rv = is.readObject(); } } catch (Exception e) { e.printStackTrace(); Constant.MY_LOG.info("deserialize error"); } finally { close(is); close(bis); } return (T) rv; } private static void close(Closeable closeable) { if (closeable != null) try { closeable.close(); } catch (IOException e) { e.printStackTrace(); Constant.MY_LOG.info("close stream error"); } }}

 

转载地址:http://wxifa.baihongyu.com/

你可能感兴趣的文章
android防止内存溢出浅析
查看>>
4.3.3版本之引擎bug
查看>>
SQL Server表分区详解
查看>>
使用FMDB最新v2.3版本教程
查看>>
STM32启动过程--启动文件--分析
查看>>
垂死挣扎还是涅槃重生 -- Delphi XE5 公布会归来感想
查看>>
淘宝的几个架构图
查看>>
linux后台运行程序
查看>>
Python异步IO --- 轻松管理10k+并发连接
查看>>
Oracle中drop user和drop user cascade的区别
查看>>
登记申请汇总
查看>>
Android Jni调用浅述
查看>>
CodeCombat森林关卡Python代码
查看>>
第一个应用程序HelloWorld
查看>>
(二)Spring Boot 起步入门(翻译自Spring Boot官方教程文档)1.5.9.RELEASE
查看>>
Shell基础之-正则表达式
查看>>
JavaScript异步之Generator、async、await
查看>>
讲讲吸顶效果与react-sticky
查看>>
c++面向对象的一些问题1 0
查看>>
售前工程师的成长---一个老员工的经验之谈
查看>>