jedis應用實例

        最近將redis整合到項目中,將redis做爲cache使用,將來進一步做爲消息推送使用。我經過jedis和spring配置實現操做redis。html

        spring配置     

 

    <!-- redis配置 -->	
    <context:property-placeholder location="classpath:setup/redis.properties" />
    
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
        <property name="maxTotal" value="${redis.pool.maxTotal}"></property>  
        <property name="maxIdle" value="${redis.pool.maxIdle}"></property>
        <property name="minIdle" value="${redis.pool.minIdle}"></property>  
        <property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}"></property>  
        <property name="minEvictableIdleTimeMillis" value="${redis.pool.minEvictableIdleTimeMillis}"></property>  
        <property name="numTestsPerEvictionRun" value="${redis.pool.numTestsPerEvictionRun}"></property>  
        <property name="timeBetweenEvictionRunsMillis" value="${redis.pool.timeBetweenEvictionRunsMillis}"></property>  
    </bean>  
  
    <bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool"  scope="singleton" >
        <constructor-arg index="0" ref="jedisPoolConfig" />
        <constructor-arg index="1">
            <list>
                <bean name="master" class="redis.clients.jedis.JedisShardInfo">
                    <constructor-arg name="host"    index="0" value="${redis.host}" />
                    <constructor-arg name="port"    index="1" value="${redis.port}" type="int"/>
                    <constructor-arg name="timeout" index="2" value="${redis.timeout}" type="int"/>
                </bean>
            </list>
        </constructor-arg>
    </bean>    

 

        咱們能夠將redis相關配置信息單獨成redis.properties文件,而後經過context:property-placeholder進行掃描,能夠經過spring相似el方式註解參數。java

        咱們同時還能夠經過制定scope屬性,配置爲單例模式redis

    scope="singleton"

 

        網上的關於JedisShardInfo的構造器配置是舊版本的。若是參數個數不正確會提示spring

 

    Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)

        同時構造器的參數名稱必須與構造器的參數保持一致,不然會提示如下錯誤信息數據庫

 

 

    Unsatisfied dependency expressed through constructor argument with index 0 of type [java.lang.String]: 
    Ambiguous constructor argument types - did you specify the correct bean references as constructor arguments?

        jedis 2.7.2中的JedisShardInfo提供瞭如下幾個構造方法express

 

 

    public JedisShardInfo(String host)
    public JedisShardInfo(String host, String name) 
    public JedisShardInfo(String host, int port)
    public JedisShardInfo(String host, int port, String name)
    public JedisShardInfo(String host, int port, int timeout)       
    public JedisShardInfo(String host, int port, int timeout, String name)    
    public JedisShardInfo(String host, int port, int connectionTimeout, int soTimeout, int weight)
    public JedisShardInfo(String host, String name, int port, int timeout, int weight)
    public JedisShardInfo(URI uri) 

 

 

  • redis.properties配置內容以下

 

#IP
redis.host=59.56.74.73
#Port
redis.port=25879
#客戶端請求超時時間,單位毫秒
redis.timeout=20000
#訪問密碼,默認沒有密碼
redis.password=
#默認的數據庫索引號
redis.database=0
#是否使用池
redis.usePool=true
    
#jedis的pool最多可管理的jedis實例
redis.pool.maxTotal=1024  
#最大的空閒jedis實例
redis.pool.maxIdle=200    
#最小空閒jedis實例
redis.pool.minIdle=0
#當池內沒有返回對象時,最大等待時間,設置爲10s
redis.pool.maxWaitMillis=10000 
#當調用borrow Object方法時,是否進行有效性檢查
redis.pool.testOnBorrow=true
#當調用return Object方法時,是否進行有效性檢查
redis.pool.testOnReturn=true

#testWhileIdle:若是爲true,表示有一個idle object evitor線程對idle object進行掃描,若是validate失敗,此object會被從pool中drop掉;
#這一項只有在timeBetweenEvictionRunsMillis大於0時纔有意義;
redis.pool.testWhileIdle=true
#表示一個對象至少停留在idle狀態的最短期,而後才能被idle object evitor掃描並驅逐;
#這一項只有在timeBetweenEvictionRunsMillis大於0時纔有意義;
redis.pool.minEvictableIdleTimeMillis=300000
#表示idle object evitor每次掃描的最多的對象數
redis.pool.numTestsPerEvictionRun=3
#表示idle object evitor兩次掃描之間要sleep的毫秒數
redis.pool.timeBetweenEvictionRunsMillis=60000

       個人jedis版本爲2.7.2,所以網上的不少maxactive和maxwait參數已經改成maxtotal和maxWaitMillis。同時jedis 2.7.2使用的是commom-pool 2版本。common-pool2的一些方法已經改變。
app

 

     redis類實現

 

/**
 * key = product:module:identity
 * */
public class Redis {
    private final static Logger logger = LoggerFactory.getLogger(Redis.class);
	
    private static ShardedJedisPool shardedJedisPool;
    
    private ShardedJedis shardedJedis;
    
    static{
		if(shardedJedisPool == null){
			ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:setup/applicationContext.xml");
			shardedJedisPool = (ShardedJedisPool) context.getBean("shardedJedisPool");			
		}    	
    }

	/*獲取sharedJedis對象*/
    private void getResource(){
    	shardedJedis = shardedJedisPool.getResource();
    	logger.info("__________________獲取sharedJedis");
    }
    
    /*釋放sharedJedis對象*/
    private void returnResource(){
    	shardedJedisPool.returnResourceObject(shardedJedis);
    
    	logger.info("__________________釋放sharedJedis");
    }
    
    /*判斷是否存在*/
    private boolean existsKey(String key){
    	if(key != null && key.trim().length() > 0){ 	
    		return shardedJedis.exists(key);
    	}else{
    		return false;
    	}
    }
    
    /*設置value*/
    public void setValue(String key, String value){
    	try{
    		getResource();
    		
			if(existsKey(key)){
				shardedJedis.set(key, value);
			}else{
				/*若key不存在,則插入該key記錄*/
				shardedJedis.setnx(key,  value);				
			}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*key中追加value值*/
    public void appendValue(String key, String value){
    	try{
    		getResource();
    		
			if(existsKey(key)){
				shardedJedis.append(key, value);
			}else{
				shardedJedis.setnx(key, value);
			}
    		
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*設定含有有效期限的value,單位爲秒*/
    public void setexValue(String key, String value, int exprise){
    	try{
    		getResource();
    		
    		if(key != null && key.trim().length() > 0){
    			shardedJedis.setex(key, exprise, value);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*讀取value*/
    public String getValue(String key){
    	try{
    		getResource();
    		
    		if(key != null && key.trim().length() > 0){
    			return shardedJedis.get(key);
    		}else{
    			return null;
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
    
    /**獲取並修改value*/
    public String getSetValue(String key, String value){
    	try{
    		getResource();
    		
			if(existsKey(key)){
				return shardedJedis.getSet(key, value);
			}else{
				setValue(key, value);
			}	
			
			return null;
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
    
    /*截取指定長度的字符串*/
    public String getRangeValue(String key, int start, int end){
    	try{
    		getResource();
    		
    		if(key != null && key.trim().length() > 0){
    			return shardedJedis.getrange(key, start, end);
    		}else{
    			return null;
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
    
    /*刪除value*/
    public void deleteValue(String key){
    	try{
    		getResource();
    		
    		if(key != null && key.trim().length() > 0){
    			shardedJedis.del(key);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*list添加元素*/
    public void pushListItem(String key, String value){
    	try{
    		getResource();
    		
    		if(key != null && key.trim().length() > 0){
    			shardedJedis.lpush(key, value);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*設置list的元素值*/
    public void setListItem(String key, int index, String value){
    	try{
    		getResource();
    		
    		shardedJedis.lset(key, index, value);
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*返回list長度*/
    public Long getListSize(String key){
    	try{
    		getResource();
    		
			if(existsKey(key)){
				return shardedJedis.llen(key);
			}
    		
    		return (long) 0;
    	}catch(Exception e){
    		e.printStackTrace();
    		return (long) 0;
    	}finally{
    		returnResource();
    	}
    }
    
    /*返回排序過的list*/
    public List<String> getSortList(String key){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			return shardedJedis.sort(key);
    		}
    		
    		return null;
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
    
    /*返回指定範圍的list*/
    public List<String> getListItemRange(String key, int start, int end){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			return shardedJedis.lrange(key, start, end);
    		}else{
    			return null;
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
    
    /*返回list指定索引的item的值*/
    public String getListItemValue(String key, int index){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			return shardedJedis.lindex("lists", index);
    		}
    		
    		return null;
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
    
    /*返回list指定範圍的list*/
    public List<String> getListRangeItems(String key){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			return shardedJedis.lrange(key, 0, -1);
    		}
    		
    		return null;
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
        
    /*刪除list的值爲value的item*/
    public void delListItem(String key, int index, String value){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			shardedJedis.lrem(key, 1, value);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*刪除list指定範圍之外的item*/
    public void deleteListRange(String key, int start, int end){
    	try{
    		getResource();
    		
    		shardedJedis.ltrim(key, start, end);
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*list第一個item出棧, 並返回該item*/
    public String getListPopItem(String key){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			return shardedJedis.lpop(key);
    		}
    		
    		return null;
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
	
    /*設置hashmap*/
    public void setMapItem(String key, HashMap<String, String> map){
    	try{
    		getResource();
    		
    		if(key != null && key.trim().length() > 0){
    			shardedJedis.hmset(key, map);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*返回hashmap的鍵個數*/
    public Long getMapLength(String key){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			return shardedJedis.hlen(key);
    		}
    		
    		return (long) 0;
    	}catch(Exception e){
    		e.printStackTrace();
    		return (long) 0;
    	}finally{
    		returnResource();
    	}
    }
    
    /*返回hashmap中的全部key*/
    public Set<String> getMapAllKeys(String key){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			return shardedJedis.hkeys(key);
    		}
    		
    		return null;
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
    
    
    /*返回hashmap中的全部value*/
    public List<String> getMapAllValues(String key){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			return shardedJedis.hvals(key);
    		}
    		
    		return null;
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }    
    
    /*獲取hashmap*/
    public List<String> getMapItem(String key, String... fields){
    	try{
    		getResource();
    		
    		return shardedJedis.hmget(key, fields);
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
   
    /*刪除map中item*/
    public void deleteMapItem(String key, String itemKey){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			shardedJedis.hdel(key, itemKey);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*事務*/
    
    /*管道*/
    
    /*管道中事物*/
}

        調用方法ide

 

	
	Redis redis = new Redis();
        redis.setValue("foo", "look here");
                
        System.out.println("____________value="+ redis.getValue("foo"));
        redis.deleteValue("foo");

 

  • 經過注入方式實現

              上面的配置信息不變,下面是注入的代碼和調用的代碼ui

 

/**
 * key = product:module:identity
 * */
@Component
public class Redis {
	private final static Logger logger = LoggerFactory.getLogger(Redis.class);
	
	/*配置bean,經過注入方式獲取切片鏈接池*/
	@Resource(name="shardedJedisPool")
        private  ShardedJedisPool shardedJedisPool;
    
    /**
	 * @return the shardedJedisPool
	 */
	public ShardedJedisPool getShardedJedisPool() {
		return shardedJedisPool;
	}

	/**
	 * @param shardedJedisPool the shardedJedisPool to set
	 */
	public void setShardedJedisPool(ShardedJedisPool shardedJedisPool) {
		this.shardedJedisPool = shardedJedisPool;
	}

	/**
	 * @return the shardedJedis
	 */
	public ShardedJedis getShardedJedis() {
		return shardedJedis;
	}

	/**
	 * @param shardedJedis the shardedJedis to set
	 */
	public void setShardedJedis(ShardedJedis shardedJedis) {
		this.shardedJedis = shardedJedis;
	}

	private ShardedJedis shardedJedis;
    
    /*獲取sharedJedis對象*/
    private void getResource(){
    	shardedJedis = shardedJedisPool.getResource();
    	logger.info("__________________獲取sharedJedis");
    }
    
    /*釋放sharedJedis對象*/
    private void returnResource(){
    	shardedJedisPool.returnResourceObject(shardedJedis);
    
    	logger.info("__________________釋放sharedJedis");
    }
    
    /*判斷是否存在*/
    private boolean existsKey(String key){
    	if(key != null && key.trim().length() > 0){ 	
    		return shardedJedis.exists(key);
    	}else{
    		return false;
    	}
    }
    
    /*設置value*/
    public void setValue(String key, String value){
    	try{
    		getResource();
    		
			if(existsKey(key)){
				shardedJedis.set(key, value);
			}else{
				/*若key不存在,則插入該key記錄*/
				shardedJedis.setnx(key,  value);				
			}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*key中追加value值*/
    public void appendValue(String key, String value){
    	try{
    		getResource();
    		
			if(existsKey(key)){
				shardedJedis.append(key, value);
			}else{
				shardedJedis.setnx(key, value);
			}
    		
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*設定含有有效期限的value,單位爲秒*/
    public void setexValue(String key, String value, int exprise){
    	try{
    		getResource();
    		
    		if(key != null && key.trim().length() > 0){
    			shardedJedis.setex(key, exprise, value);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*讀取value*/
    public String getValue(String key){
    	try{
    		getResource();
    		
    		if(key != null && key.trim().length() > 0){
    			return shardedJedis.get(key);
    		}else{
    			return null;
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
    
    /**獲取並修改value*/
    public String getSetValue(String key, String value){
    	try{
    		getResource();
    		
			if(existsKey(key)){
				return shardedJedis.getSet(key, value);
			}else{
				setValue(key, value);
			}	
			
			return null;
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
    
    /*截取指定長度的字符串*/
    public String getRangeValue(String key, int start, int end){
    	try{
    		getResource();
    		
    		if(key != null && key.trim().length() > 0){
    			return shardedJedis.getrange(key, start, end);
    		}else{
    			return null;
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
    
    /*刪除value*/
    public void deleteValue(String key){
    	try{
    		getResource();
    		
    		if(key != null && key.trim().length() > 0){
    			shardedJedis.del(key);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*list添加元素*/
    public void pushListItem(String key, String value){
    	try{
    		getResource();
    		
    		if(key != null && key.trim().length() > 0){
    			shardedJedis.lpush(key, value);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*設置list的元素值*/
    public void setListItem(String key, int index, String value){
    	try{
    		getResource();
    		
    		shardedJedis.lset(key, index, value);
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*返回list長度*/
    public Long getListSize(String key){
    	try{
    		getResource();
    		
			if(existsKey(key)){
				return shardedJedis.llen(key);
			}
    		
    		return (long) 0;
    	}catch(Exception e){
    		e.printStackTrace();
    		return (long) 0;
    	}finally{
    		returnResource();
    	}
    }
    
    /*返回排序過的list*/
    public List<String> getSortList(String key){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			return shardedJedis.sort(key);
    		}
    		
    		return null;
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
    
    /*返回指定範圍的list*/
    public List<String> getListItemRange(String key, int start, int end){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			return shardedJedis.lrange(key, start, end);
    		}else{
    			return null;
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
    
    /*返回list指定索引的item的值*/
    public String getListItemValue(String key, int index){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			return shardedJedis.lindex("lists", index);
    		}
    		
    		return null;
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
    
    /*返回list指定範圍的list*/
    public List<String> getListRangeItems(String key){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			return shardedJedis.lrange(key, 0, -1);
    		}
    		
    		return null;
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
        
    /*刪除list的值爲value的item*/
    public void delListItem(String key, int index, String value){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			shardedJedis.lrem(key, 1, value);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*刪除list指定範圍之外的item*/
    public void deleteListRange(String key, int start, int end){
    	try{
    		getResource();
    		
    		shardedJedis.ltrim(key, start, end);
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*list第一個item出棧, 並返回該item*/
    public String getListPopItem(String key){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			return shardedJedis.lpop(key);
    		}
    		
    		return null;
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
	
    /*設置hashmap*/
    public void setMapItem(String key, HashMap<String, String> map){
    	try{
    		getResource();
    		
    		if(key != null && key.trim().length() > 0){
    			shardedJedis.hmset(key, map);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*返回hashmap的鍵個數*/
    public Long getMapLength(String key){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			return shardedJedis.hlen(key);
    		}
    		
    		return (long) 0;
    	}catch(Exception e){
    		e.printStackTrace();
    		return (long) 0;
    	}finally{
    		returnResource();
    	}
    }
    
    /*返回hashmap中的全部key*/
    public Set<String> getMapAllKeys(String key){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			return shardedJedis.hkeys(key);
    		}
    		
    		return null;
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
    
    
    /*返回hashmap中的全部value*/
    public List<String> getMapAllValues(String key){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			return shardedJedis.hvals(key);
    		}
    		
    		return null;
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }    
    
    /*獲取hashmap*/
    public List<String> getMapItem(String key, String... fields){
    	try{
    		getResource();
    		
    		return shardedJedis.hmget(key, fields);
    	}catch(Exception e){
    		e.printStackTrace();
    		return null;
    	}finally{
    		returnResource();
    	}
    }
   
    /*刪除map中item*/
    public void deleteMapItem(String key, String itemKey){
    	try{
    		getResource();
    		
    		if(existsKey(key)){
    			shardedJedis.hdel(key, itemKey);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		returnResource();
    	}
    }
    
    /*事務*/
    
    /*管道*/
    
    /*管道中事物*/
}

       調用方法this

 

 

	@Resource
	Redis redis;
        redis.setValue("foo", "look here");
                
        System.out.println("____________value="+ redis.getValue("foo"));
        redis.deleteValue("foo");
相關文章
相關標籤/搜索