类定义的时候使用泛型,可以使里面的成员方法,灵活的变成调用地方传入的类型
应用:
package com.houbank.incoming.service.impl; import com.houbank.incoming.service.redis.RedisTemplateDelegate; import org.springframework.beans.factory.annotation.Autowired; import com.alibaba.dubbo.config.annotation.Service; import com.houbank.basic.util.redis.RedisClient; import com.houbank.basic.util.redis.exception.RedisAccessException; import com.houbank.incoming.api.CacheFacade; import com.houbank.incoming.service.processor.cache.CodeLibaryCacheManage; import com.houbank.incoming.service.processor.cache.CoreBusinessTypeCacheManage; import com.houbank.incoming.service.processor.cache.OrgInfoCacheManage; import com.houbank.incoming.service.processor.cache.ProvinceCityCacheManage; import java.util.concurrent.TimeUnit; /** * * <p>缓存操作实现</p> * @author houzhanshan * @version $Id: CacheFacadeImp.java, v 0.1 2017年6月15日 下午6:29:25 Exp $ */ @Service public class CacheFacadeImp implements CacheFacade { @Autowired private RedisTemplateDelegate redisTemplateDelegate; @Autowired private CodeLibaryCacheManage codeLibaryCacheManage; @Autowired private CoreBusinessTypeCacheManage coreBusinessTypeCacheManage; @Autowired private ProvinceCityCacheManage provinceCityCacheManage; @Autowired private OrgInfoCacheManage orgInfoCacheManage; /** * 初始化指定表的缓存 */ @Override public void initAllCacheKey() { //codeLibaryCacheManage.initCache(); //coreBusinessTypeCacheManage.initCache(); //orgInfoCacheManage.initCache(); provinceCityCacheManage.initCache(); } @Override public void del(String key) throws RedisAccessException { // return redisClient.del(key); redisTemplateDelegate.delete(key); } @Override public void set(String key, String value) throws RedisAccessException { // return redisClient.set(key, value); redisTemplateDelegate.set(key, value); } @Override public Object get(String key) throws RedisAccessException { // return redisClient.get(key); return redisTemplateDelegate.get(key); } @Override public void set(String key, String value, int timeout) throws RedisAccessException { // return redisClient.set(key, value,timeout); redisTemplateDelegate.set(key, value,timeout); } @Override public void setObject(String key, Object object) throws RedisAccessException { // return redisClient.setObject(key, object); redisTemplateDelegate.set(key, object); } @Override public void setObject(String key, Object object, int timeout) throws RedisAccessException { // return redisClient.setObject(key, object,timeout); redisTemplateDelegate.set(key, object,timeout, TimeUnit.MINUTES); } @Override public Object getObject(String key) throws RedisAccessException { // return redisClient.getObject(key); return redisTemplateDelegate.get(key); } }
模板:
package com.houbank.incoming.service.redis; import lombok.extern.log4j.Log4j2; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.redis.connection.DataType; import org.springframework.data.redis.connection.MessageListener; import org.springframework.data.redis.core.RedisConnectionUtils; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisMonitor; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.*; import java.util.concurrent.TimeUnit; /** * * <p>redis模板代理类</p> * @author houzhanshan * @version $Id: RedisTemplateDelegate.java, v 0.1 2017年5月26日 下午11:40:13 houzhanshan Exp $ */ @Log4j2 public class RedisTemplateDelegate<K,V> { private static final String LINE_SEPARATOR = System.getProperty("line.separator"); private static final String DEFAULT_CHARSET = "utf-8"; private static final byte[][] EMPTY_2D_BYTE_ARRAY = new byte[0][]; private static Logger log= LoggerFactory.getLogger(RedisTemplateDelegate.class); private RedisTemplate<String, V> redisTemplate; private ValueOperations<String, V> valueOperations; public void setRedisTemplate(RedisTemplate<String, V> redisTemplate) { this.redisTemplate = redisTemplate; this.valueOperations = redisTemplate.opsForValue(); RedisSerializer<String> stringSerializer = new StringRedisSerializer(); this.redisTemplate.setKeySerializer(stringSerializer); // this.redisTemplate.setHashKeySerializer(stringSerializer); } public void set(String key, V value) { valueOperations.set(key, value); } public boolean set(String key, V value, long timeout, TimeUnit unit) { try { valueOperations.set(key, value, timeout, unit); // redisTemplate.getConnectionFactory().getConnection().close(); } catch (Throwable e) { log.error("", e); return false; } return true; } public Boolean setIfAbsent(String key, V value) { return valueOperations.setIfAbsent(key, value); } public void multiSet(Map<? extends String, ? extends V> m) {//MSET valueOperations.multiSet(m); } public Boolean multiSetIfAbsent(Map<? extends String, ? extends V> m) { return valueOperations.multiSetIfAbsent(m); } public V get(String key) { // V temp=null; // try { return valueOperations.get(key); // }catch (Exception e){ // // }finally { // redisTemplate.getConnectionFactory().getConnection().close(); // } // return temp; } public V getAndSet(String key, V value) {//GETSET return valueOperations.getAndSet(key, value); } public List<V> multiGet(Collection<String> keys) {//MGET return valueOperations.multiGet(keys); } public Map<String, V> multiGetMap(List<String> keys) { int size = 0; if (keys == null || (size = keys.size()) <= 0) { return new HashMap<String, V>(); } Map<String, V> kvMap = new HashMap<String, V>(); List<V> values = valueOperations.multiGet(keys); for (int i = 0; i < size; i++) { kvMap.put(keys.get(i), values.get(i)); } return kvMap; } public Long increment(String key, long delta) { return valueOperations.increment(key, delta); } public Double increment(String key, double delta) { return valueOperations.increment(key, delta); } public Integer append(String key, String value) { return valueOperations.append(key, value); } public String get(String key, long start, long end) { return valueOperations.get(key, start, end); } public void set(String key, V value, long offset) { valueOperations.set(key, value, offset); } public Long size(String key) { return valueOperations.size(key); } public Boolean setBit(String key, long offset, boolean value) { return valueOperations.setBit(key, offset, value); } public Boolean getBit(String key, long offset) { return valueOperations.getBit(key, offset); } public void delete(String key) { this.redisTemplate.delete(key); } public void delete(Collection<String> keys) { this.redisTemplate.delete(keys); } public void remove(String key) { this.delete(key); } public void remove(Collection<String> keys) { this.delete(keys); } public Boolean hasKey(String key) { return this.redisTemplate.hasKey(key); } public Boolean persist(String key) { return this.redisTemplate.persist(key); } public Boolean expire(String key, final long timeout, final TimeUnit unit) { return this.redisTemplate.expire(key, timeout, unit); } public Boolean expireAt(String key, final Date date) { return this.redisTemplate.expireAt(key, date); } public Long getExpire(String key) { return this.redisTemplate.getExpire(key); } public Long getExpire(String key, final TimeUnit timeUnit) { return this.redisTemplate.getExpire(key, timeUnit); } public Boolean move(String key, final int dbIndex) { return this.redisTemplate.move(key, dbIndex); } public String randomKey() { return this.redisTemplate.randomKey(); } public void rename(String oldKey, String newKey) { this.redisTemplate.rename(oldKey, newKey); } public Boolean renameIfAbsent(String oldKey, String newKey) { return this.redisTemplate.renameIfAbsent(oldKey, newKey); } public DataType type(String key) { return this.redisTemplate.type(key); } public void restore(String key, final byte[] value, long timeToLive, TimeUnit unit) { this.redisTemplate.restore(key, value, timeToLive, unit); } public void publish(String channel, Object message) { redisTemplate.convertAndSend(channel, message); } /* private void multi() { this.redisTemplate.multi(); } private void discard() { this.redisTemplate.discard(); } private List<Object> exec() { return this.redisTemplate.exec(); }*/ /* public void multiSet(Map<? extends String, ? extends V> m, long timeout, TimeUnit unit) { transaction(new Executor<Object>() { @Override public Object run() { valueOperations.multiSet(m); for (String key : m.keySet()) { expire(key, timeout, unit); } return null; } }); }*/ public void monitor(String regex) { monitor(null, regex); } public void monitor(File file) { monitor(file, null); } public void monitor(File file, final String regex) { OutputStreamWriter osw = null; try { if (file != null) { osw = new OutputStreamWriter(new FileOutputStream(file), DEFAULT_CHARSET); } final OutputStreamWriter oswInner = osw; monitor(new JedisMonitor() { public void onCommand(String command) { //command example: 1489465990.254438 [0 127.0.0.1:53010] "set" "aaa" "bbb" String realCommand = command.substring(command.indexOf("]") + 2); if ((StringUtils.isNotEmpty(regex) && realCommand.matches(regex)) || (StringUtils.isEmpty(regex))) { System.out.println(command); if (oswInner != null) { try { oswInner.write(command + LINE_SEPARATOR); oswInner.flush(); } catch (Throwable e) { log.error("", e); } } } } }); } catch (Throwable e) { log.error("", e); } finally { try { if (osw != null) { osw.flush(); osw.close(); } } catch (Throwable e) { } } } public void monitor() { monitor(new JedisMonitor() { public void onCommand(String command) { System.out.println(command); } }); } public void monitor(final JedisMonitor jedisMonitor) { Jedis jedis = null; try { Object nativeConn = RedisConnectionUtils.getConnection(this.redisTemplate.getConnectionFactory()).getNativeConnection(); if (nativeConn instanceof Jedis) { jedis = (Jedis) nativeConn; jedis.monitor(jedisMonitor); } } catch (Throwable e) { if (jedis != null) { jedis.close(); } log.error("", e); } } public void subscribe(MessageListener listener, String... channels) { try { RedisConnectionUtils.getConnection(this.redisTemplate.getConnectionFactory()).subscribe(listener, serializeMulti(channels)); } catch (Throwable e) { log.error("", e); } } public void pSubscribe(MessageListener listener, String... patterns) { try { RedisConnectionUtils.getConnection(this.redisTemplate.getConnectionFactory()).pSubscribe(listener, serializeMulti(patterns)); } catch (Throwable e) { log.error("", e); } } private byte[][] serializeMulti(String... keys) throws UnsupportedEncodingException { if (keys == null) { return EMPTY_2D_BYTE_ARRAY; } byte[][] ret = new byte[keys.length][]; for (int i = 0; i < ret.length; i++) { ret[i] = keys[i].getBytes(DEFAULT_CHARSET); } return ret; } /*private <T> T transaction(Executor<T> executor) { return this.redisTemplate.execute(new SessionCallback<T>() { @Override public <OK, OV> T execute(RedisOperations<OK, OV> operations) throws DataAccessException { try { redisTemplate.multi(); T result = executor.run(); redisTemplate.exec(); return result; } catch (Throwable e) { log.error("", e); redisTemplate.discard(); return null; } } }); } */ public void watch(String key) { this.redisTemplate.watch(key); } public Set<String> keys(String pattern) {//keys pattern return this.redisTemplate.keys(pattern); } /*public List<V> multiGet(Collection<String> pattern) {//keys pattern return this.valueOperations.multiGet(pattern); }*/ /*public <HK, HV> HashOperations<HK, HV> hash(String key) { return new HashOperations<HK, HV>(this.redisTemplate.boundHashOps(key)); } public <HK, HV> HashOperations<HK, HV> map(String key) { return new HashOperations<HK, HV>(this.redisTemplate.boundHashOps(key)); } public ListOperations<V> list(String key) { return new ListOperations<V>(this.redisTemplate.boundListOps(key)); } public SetOperations<V> set(String key) { return new SetOperations<V>(this.redisTemplate.boundSetOps(key)); } public ZSetOperations<V> zset(String key) { return new ZSetOperations<V>(this.redisTemplate.boundZSetOps(key)); }*/ }