`
y806839048
  • 浏览: 1106805 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

类的泛型使用

 
阅读更多

类定义的时候使用泛型,可以使里面的成员方法,灵活的变成调用地方传入的类型

 

 

应用:

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));
   }*/
}




分享到:
评论

相关推荐

    C#泛型类、泛型方法、泛型接口、泛型委托的实例

    本文将深入探讨泛型类、泛型方法、泛型接口和泛型委托,并通过实例来阐述它们的应用。 首先,我们来看泛型类。泛型类是具有一个或多个类型参数的类。类型参数是在定义类时使用的占位符,实际的类型在创建类的实例时...

    【Flutter】Dart 泛型 ( 泛型类 泛型方法 特定类型约束的泛型 ).zip

    【Flutter】Dart 泛型 ( 泛型类 | 泛型方法 | 特定类型约束的泛型 ) https://hanshuliang.blog.csdn.net/article/details/114059611 博客源码快照

    集合类泛型类

    Java集合类中的泛型使用有几种常见形式: - **无界通配符**:`?` 表示可以接受任何类型的对象。例如,`List&lt;?&gt;` 可以表示任何类型的列表。 - **上限通配符**:`? extends T` 表示可以接受T或T的子类对象。例如,`...

    C# 工具类 泛型转JSON(Newtonsoft.Json)

    C# 工具类 泛型转JSON 使用 Newtonsoft.Json 转换JSON

    java 继承泛型类示例

    在Java编程语言中,泛型是一种强大的特性,它允许我们在类、接口和方法中使用类型参数,从而提高代码的灵活性和安全性。当我们谈论“继承泛型类”时,这意味着一个类(子类)正在扩展一个已经定义了泛型的类(父类)...

    c#泛型类、泛型方法、泛型接口、泛型委托

    在C#编程语言中,泛型是...通过使用泛型类、方法、接口和委托,我们可以编写灵活且类型安全的代码,适用于多种数据类型,同时减少运行时类型检查和转换的成本。在实际开发中,熟练掌握泛型能极大提升代码质量和维护性。

    泛型工具类

    想象一个基于Spring框架的Java应用程序,其中使用了泛型的DAO层来处理各种实体类的数据操作。在这样的场景下,`GenericUtil`类可以被用来动态获取每个DAO实例所处理的实体类型,进而执行特定于该类型的数据库操作,...

    c#使用 和 继承 泛型类

    本篇文章将深入探讨如何在C#中使用和继承泛型类。 首先,让我们理解什么是泛型类。泛型类是一种模板或蓝图,它定义了参数化类型,这些类型在类实例化时可以被具体的类型替换。在C#中,我们使用尖括号`&lt;&gt;`来声明泛型...

    c# 泛型的使用,教你如何用泛型

    本篇文章将深入探讨C#中的泛型使用方法,帮助你更好地理解和应用这一关键概念。 首先,我们需要理解什么是泛型。泛型允许我们在定义类、接口、委托和方法时,不指定具体的类型参数,而是使用一个占位符,如`T`、`K`...

    Java中泛型的各种使用

    泛型是Java SE 5.0引入的新特性,它允许在类、接口和方法中使用类型参数。类型参数类似于函数参数,但它们代表的是类型而不是值。例如,`List&lt;T&gt;`中的`T`就是一个类型参数,`T`代表某种具体的类型,如`String`、`...

    myreflect.rar 反射和泛型使用源码

    1. **类型参数**:定义泛型类或接口时,使用尖括号`&lt;T&gt;`表示类型参数,T是占位符,代表任意类型。 2. **通配符**:如`?`,表示未知类型,常用于方法参数,提供更大的灵活性。 3. **边界**:`&lt;T extends SomeClass&gt;`...

    Java泛型使用详细分析.pdf

    Java 泛型使用详细分析 Java 泛型是 Java 语言中的一种类型系统特性,允许开发者在编译期检查类型安全,以避免在运行时出现类型相关的错误。在本文中,我们将详细介绍 Java 泛型的使用方法和实现原理。 一、泛型的...

    java 继承非泛型类示例

    当我们谈论继承非泛型类时,意味着子类继承了一个没有使用泛型的父类。泛型是Java SE 5.0引入的新特性,用于提供类型安全和减少强制类型转换,但并不是所有类都必须使用泛型。 非泛型类通常定义为不包含类型参数的...

    泛型和泛型集合类用法

    除了使用内置的泛型集合类之外,还可以自定义泛型类。例如: ```csharp public class ItemList { private List&lt;T&gt; items = new List(); public void Add(T item) { items.Add(item); } public T Get(int ...

    利用反射生成泛型类对象

    对于框架设计者来说,便捷的代码,是很重要的一部分。 反射和泛型是一种重要的解决途径。 此代码是一个生成泛型对象的类。...希望能帮助那些为查找泛型构造器、非静态内部泛型类的对象生成而烦恼的童鞋。

    C#泛型集合使用实例

    C#中的泛型接口如`IEnumerable&lt;T&gt;`和泛型类如`List&lt;T&gt;`、`Dictionary, TValue&gt;`是泛型集合的基础。这些接口和类定义了操作数据的一般方法,而`T`则代表一个未指定的类型参数,可以在实例化时指定具体类型。 2. **...

    DropDownList无极分类 用泛型

    总的来说,这个项目涉及了ASP.NET Web Forms、C#编程、数据库交互、泛型使用以及分层架构的设计。通过使用泛型,可以创建灵活且类型安全的函数,处理多种类型的数据,同时实现DropDownList的无极分类功能,提高代码...

    泛型集合泛型集合泛型集合

    泛型的概念源自英文"Generic",直译为“通用”,在C#中,它使得开发者能够在不指定具体类型的情况下编写类、接口、方法等,待实际使用时再指定具体的类型。这种设计大大增强了类型安全性,避免了不必要的类型转换和...

    java 泛型方法使用示例

    泛型方法是泛型技术在类方法层面的应用,它允许我们定义一个可以处理多种数据类型的通用方法。下面我们将深入探讨Java泛型方法的概念、语法以及使用示例。 **一、泛型方法概念** 泛型方法是一种具有类型参数的方法...

    java 泛型类的类型识别示例

    4. **利用`Class&lt;T&gt;`作为泛型约束**:有时候,我们可以在泛型类中使用`Class&lt;T&gt;`作为参数或字段,这样可以在运行时获取类型信息。例如: ```java public class MyClass&lt;T&gt; { private final Class&lt;T&gt; clazz; ...

Global site tag (gtag.js) - Google Analytics