1. 程式人生 > >java中使用Jedis操作Redis例項

java中使用Jedis操作Redis例項

要想在Java中連線Redis,並進行操作,由兩種方式,一種是spring data redis,它是由spring整合的,不支援叢集,一種是官方推薦的jedis,支援叢集,其他功能差不多一樣,

這裡我們介紹jedis操作例項,以下是使用Jedis的具體步驟:

1、如果是在Maven專案中,在pom.xml中增加如下語句,如果不是Maven專案下載包匯入專案即可:

<dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.6.2</version>
        </dependency>

2、建立redis.properties配置檔案,設定連線引數
# Redis settings  
redis.host=192.168.0.240
redis.port=6379
redis.pass=xxxxxx
redis.timeout=10000

redis.maxIdle=300
redis.maxTotal=600
# 毫秒
redis.maxWaitMillis=1000
redis.testOnBorrow=false

3、建立屬性檔案載入工具類,用於獲取redis.properties檔案

package com.rmd.cart.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 屬性檔案載入工具類
 * @author lc
 */
public class PropertyUtil {
   
    //載入property檔案到io流裡面
    public static Properties loadProperties(String propertyFile) {
    	Properties properties = new Properties();
        try {
            InputStream is = PropertyUtil.class.getClassLoader().getResourceAsStream(propertyFile);
            if(is == null){
            	is = PropertyUtil.class.getClassLoader().getResourceAsStream("properties/" + propertyFile);
            }
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }

    /**
     * 根據key值取得對應的value值
     *
     * @param key
     * @return
     */
    public static String getValue(String propertyFile, String key) {
    	Properties properties = loadProperties(propertyFile);
        return properties.getProperty(key);
    }
}

4、建立連線redis工具類
package com.rmd.cart.utils;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * redis工具類
 * @author lc
 */
public class JedisUtil {
    private static JedisPool jedisPool = null;

    private JedisUtil() {

    }
    
    //寫成靜態程式碼塊形式,只加載一次,節省資源
    static {
        Properties properties = PropertyUtil.loadProperties("redis.properties");
        String host = properties.getProperty("redis.host");
        String port = properties.getProperty("redis.port");
        String pass = properties.getProperty("redis.pass");
        String timeout = properties.getProperty("redis.timeout");
        String maxIdle = properties.getProperty("redis.maxIdle");
        String maxTotal = properties.getProperty("redis.maxTotal");
        String maxWaitMillis = properties.getProperty("redis.maxWaitMillis");
        String testOnBorrow = properties.getProperty("redis.testOnBorrow");

        JedisPoolConfig config = new JedisPoolConfig();
        //控制一個pool可分配多少個jedis例項,通過pool.getResource()來獲取;
        //如果賦值為-1,則表示不限制;如果pool已經分配了maxActive個jedis例項,則此時pool的狀態為exhausted(耗盡)。
        config.setMaxTotal(Integer.parseInt(maxTotal));
        //控制一個pool最多有多少個狀態為idle(空閒的)的jedis例項。
        config.setMaxIdle(Integer.parseInt(maxIdle));
        //表示當borrow(引入)一個jedis例項時,最大的等待時間,如果超過等待時間,則直接丟擲JedisConnectionException;
        config.setMaxWaitMillis(Long.parseLong(maxWaitMillis));
        //在borrow一個jedis例項時,是否提前進行validate操作;如果為true,則得到的jedis例項均是可用的;
        config.setTestOnBorrow(Boolean.valueOf(testOnBorrow));

        jedisPool = new JedisPool(config, host, Integer.parseInt(port), Integer.parseInt(timeout), pass);
    }

    /**
     * 從jedis連線池中獲取獲取jedis物件
     *
     * @return
     */
    private Jedis getJedis() {
        return jedisPool.getResource();
    }

    private static final JedisUtil jedisUtil = new JedisUtil();

    /**
     * 獲取JedisUtil例項
     *
     * @return
     */
    public static JedisUtil getInstance() {
        return jedisUtil;
    }

    /**
     * 回收jedis(放到finally中)
     *
     * @param jedis
     */
    private void returnJedis(Jedis jedis) {
        if (null != jedis && null != jedisPool) {
            jedisPool.returnResource(jedis);
        }
    }

    /**
     * 銷燬連線(放到catch中)
     *
     * @param jedis
     */
    private static void returnBrokenResource(Jedis jedis) {
        if (null != jedis && null != jedisPool) {
            jedisPool.returnResource(jedis);
        }
    }

    /**
     * 新增sorted set
     *
     * @param key
     * @param value
     * @param score
     */
    public void zadd(String key, String value, double score) {
        Jedis jedis = getJedis();
        jedis.zadd(key, score, value);
        returnJedis(jedis);
    }

    /**
     * 返回指定位置的集合元素,0為第一個元素,-1為最後一個元素
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<String> zrange(String key, int start, int end) {
        Jedis jedis = getJedis();
        Set<String> set = jedis.zrange(key, start, end);
        returnJedis(jedis);
        return set;
    }

    /**
     * 獲取給定區間的元素,原始按照權重由高到低排序
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<String> zrevrange(String key, int start, int end) {
        Jedis jedis = getJedis();
        Set<String> set = jedis.zrevrange(key, start, end);
        returnJedis(jedis);
        return set;
    }

    /**
     * 新增對應關係,如果對應關係已存在,則覆蓋
     *
     * @param key
     * @param map 對應關係
     * @return 狀態,成功返回OK
     */
    public String hmset(String key, Map<String, String> map) {
        Jedis jedis = getJedis();
        String s = jedis.hmset(key, map);
        returnJedis(jedis);
        return s;
    }

    /**
     * 向List頭部追加記錄
     *
     * @param key
     * @param value
     * @return 記錄總數
     */
    public long rpush(String key, String value) {
        Jedis jedis = getJedis();
        long count = jedis.rpush(key, value);
        returnJedis(jedis);
        return count;
    }

    /**
     * 向List頭部追加記錄
     *
     * @param key
     * @param value
     * @return 記錄總數
     */
    private long rpush(byte[] key, byte[] value) {
        Jedis jedis = getJedis();
        long count = jedis.rpush(key, value);
        returnJedis(jedis);
        return count;
    }

    /**
     * 刪除
     *
     * @param key
     * @return
     */
    public long del(String key) {
        Jedis jedis = getJedis();
        long s = jedis.del(key);
        returnJedis(jedis);
        return s;
    }

    /**
     * 從集合中刪除成員
     * @param key
     * @param value
     * @return 返回1成功
     * */
    public long zrem(String key, String... value) {
        Jedis jedis = getJedis();
        long s = jedis.zrem(key, value);
        returnJedis(jedis);
        return s;
    }
    
    public void saveValueByKey(int dbIndex, byte[] key, byte[] value, int expireTime)
            throws Exception {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            jedis.set(key, value);
            if (expireTime > 0)
                jedis.expire(key, expireTime);
        } catch (Exception e) {
            isBroken = true;
            throw e;
        } finally {
            returnResource(jedis, isBroken);
        }
    }
    
    public byte[] getValueByKey(int dbIndex, byte[] key) throws Exception {
        Jedis jedis = null;
        byte[] result = null;
        boolean isBroken = false;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            result = jedis.get(key);
        } catch (Exception e) {
            isBroken = true;
            throw e;
        } finally {
            returnResource(jedis, isBroken);
        }
        return result;
    }
    
    public void deleteByKey(int dbIndex, byte[] key) throws Exception {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            jedis.del(key);
        } catch (Exception e) {
            isBroken = true;
            throw e;
        } finally {
            returnResource(jedis, isBroken);
        }
    }
    
    public void returnResource(Jedis jedis, boolean isBroken) {
        if (jedis == null)
            return;
        if (isBroken)
        	jedisPool.returnBrokenResource(jedis);
        else
        	jedisPool.returnResource(jedis);
    }
    
    /**
     * 獲取總數量
     * @param key
     * @return
     */
    public long zcard(String key) {
        Jedis jedis = getJedis();
        long count = jedis.zcard(key);
        returnJedis(jedis);
        return count;
    }

    /**
     * 是否存在KEY
     * @param key
     * @return
     */
    public boolean exists(String key) {
        Jedis jedis = getJedis();
        boolean exists = jedis.exists(key);
        returnJedis(jedis);
        return exists;
    }

    /**
     * 重新命名KEY
     * @param oldKey
     * @param newKey
     * @return
     */
    public String rename(String oldKey, String newKey) {
        Jedis jedis = getJedis();
        String result = jedis.rename(oldKey, newKey);
        returnJedis(jedis);
        return result;
    }

    /**
     * 設定失效時間
     * @param key
     * @param seconds
     */
    public void expire(String key, int seconds) {
        Jedis jedis = getJedis();
        jedis.expire(key, seconds);
        returnJedis(jedis);
    }

    /**
     * 刪除失效時間
     * @param key
     */
    public void persist(String key) {
        Jedis jedis = getJedis();
        jedis.persist(key);
        returnJedis(jedis);
    }
    
    /**
     * 新增一個鍵值對,如果鍵存在不在新增,如果不存在,新增完成以後設定鍵的有效期
     * @param key
     * @param value
     * @param timeOut
     */
    public void setnxWithTimeOut(String key,String value,int timeOut){
    	Jedis jedis = getJedis();
    	if(0!=jedis.setnx(key, value)){
			jedis.expire(key, timeOut);
		}
        returnJedis(jedis);
    }
    
    /**
     * 返回指定key序列值 
     * @param key
     * @return
     */
    public long incr(String key){
    	Jedis jedis = getJedis();
    	long l = jedis.incr(key);
        returnJedis(jedis);
        return l;
    }
    
    /**
     * 獲取當前時間 
     * @return 秒
     */
    public long currentTimeSecond(){
    	Long l = 0l;
    	Jedis jedis = getJedis();
    	Object obj = jedis.eval("return redis.call('TIME')",0);
    	if(obj != null){
    		List<String> list = (List)obj;
    		l = Long.valueOf(list.get(0));
    	}
        returnJedis(jedis);
        return l;
    }
}

5、編寫redis服務類
package com.rmd.cart.service.impl;
import java.util.Date;
import java.util.Set;
import org.springframework.stereotype.Service;
import com.rmd.cart.utils.JedisUtil;

/**
 * redis服務
 * @author lc
 */
@Service("redisService")
public class RedisService {

    /**
     * 新增SortSet型資料
     * @param key
     * @param value
     */
    public void addSortSet(String key, String value) {
        double score = new Date().getTime();
        JedisUtil jedisUtil = JedisUtil.getInstance();
        jedisUtil.zadd(key, value, score);
    }

    /**
     * 獲取倒序的SortSet型的資料
     * @param key
     * @return
     */
    public Set<String> getDescSortSet(String key) {
        JedisUtil jedisUtil = JedisUtil.getInstance();
        return jedisUtil.zrevrange(key, 0, -1);
    }

    /**
     * 刪除SortSet型資料
     * @param key
     * @param value
     */
    public void deleteSortSet(String key, String value) {
        JedisUtil jedisUtil = JedisUtil.getInstance();
        jedisUtil.zrem(key, value);
    }

    /**
     * 批量刪除SortSet型資料
     * @param key
     * @param value
     */
    public void deleteSortSetBatch(String key, String[] value) {
        JedisUtil jedisUtil = JedisUtil.getInstance();
        jedisUtil.zrem(key, value);
    }
    
    /**
     * 範圍獲取倒序的SortSet型的資料
     * @param key
     * @return
     */
    public Set<String> getDescSortSetPage(String key,int start, int end) {
        JedisUtil jedisUtil = JedisUtil.getInstance();
        return jedisUtil.zrevrange(key, start, end);
    }

    /**
     * 獲取SortSet型的總數量
     * @param key
     * @return
     */
    public long getSortSetAllCount(String key) {
        JedisUtil jedisUtil = JedisUtil.getInstance();
        return jedisUtil.zcard(key);
    }

    /**
     * 檢查KEY是否存在
     * @param key
     * @return
     */
    public boolean checkExistsKey(String key) {
        JedisUtil jedisUtil = JedisUtil.getInstance();
        return jedisUtil.exists(key);
    }

    /**
     * 重新命名KEY
     * @param oldKey
     * @param newKey
     * @return
     */
    public String renameKey(String oldKey, String newKey) {
        JedisUtil jedisUtil = JedisUtil.getInstance();
        return jedisUtil.rename(oldKey, newKey);
    }

    /**
     * 刪除KEY
     * @param key
     */
    public void deleteKey(String key) {
        JedisUtil jedisUtil = JedisUtil.getInstance();
        jedisUtil.del(key);
    }

    /**
     * 設定失效時間
     * @param key
     * @param seconds 失效時間,秒
     */
    public void setExpireTime(String key, int seconds) {
        JedisUtil jedisUtil = JedisUtil.getInstance();
        jedisUtil.expire(key, seconds);
    }

    /**
     * 刪除失效時間
     * @param key
     */
    public void deleteExpireTime(String key) {
        JedisUtil jedisUtil = JedisUtil.getInstance();
        jedisUtil.persist(key);
    }
}
注意:以上是公共基礎,下面是我業務操作,怎樣儲存資料和獲取資料


6、由於我想做購物車,建立購物車service介面,程式碼如下

package com.rmd.cart.service;

import java.util.Set;


/**
 * @Description: 購物車service
 * @author lc
 */
public interface CartService {
	
	/**
	 * 
	 * @Description: 新增購物車
	 * @author lc
	 * @param customerId
	 * void
	 */
    public void add(String customerId);
    
    /**
     * @Description: 獲取購物車資料
     * @author lc
     * @param customerId
     * @return
     * Set<String>
     */
    public Set<String> getCart(String customerId);

}

7、建立impl類實現service介面,程式碼如下
package com.rmd.cart.service.impl;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.rmd.cart.service.CartService;

@Service("cartService")
public class CartServiceImpl implements CartService {
	
    @Autowired
    private RedisService redisService;

	@Override
	public void add(String customerId) {
		redisService.addSortSet("rmd_cart_test123", customerId);
	}

	@Override
	public Set<String> getCart(String customerId) {
		return redisService.getDescSortSet("rmd_cart_test123");
	}

}

8、建立一個物件類,使用者資料測試
package com.rmd.cart.bean;

import java.io.Serializable;
import java.util.List;

public class SpuInfo implements Serializable{
	
	private Integer spuid;//spuid
	private long createTime;//新增時間
	private List<SkuInfo> skuList;//sku資訊集合
	
	public Integer getSpuid() {
		return spuid;
	}
	public void setSpuid(Integer spuid) {
		this.spuid = spuid;
	}
	public long getCreateTime() {
		return createTime;
	}
	public void setCreateTime(long createTime) {
		this.createTime = createTime;
	}
	public List<SkuInfo> getSkuList() {
		return skuList;
	}
	public void setSkuList(List<SkuInfo> skuList) {
		this.skuList = skuList;
	}
}

9、建立測試類,使用junit4進行測試

新增資料

package rmd_cart_provider.service.test;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import javax.annotation.Resource;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.rmd.cart.bean.SpuInfo;
import com.rmd.cart.service.CartService;

@RunWith(SpringJUnit4ClassRunner.class)  //使用junit4進行測試
@ContextConfiguration({"/applicationContext.xml"}) //載入配置檔案
public class CartTest {


    @Resource  
    private CartService cartService;

    @Test   
    public void test() throws JsonGenerationException, JsonMappingException, IOException{
    	
    	SpuInfo spu = new SpuInfo();
    	spu.setSpuid(123);
    	spu.setCreateTime(105456464);
    	
    	//將物件轉換成json字串
    	ObjectMapper om = new ObjectMapper();
        Writer wr = new StringWriter();
        om.writeValue(wr, spu);
        
        String str = wr.toString();
        //新增資料
    	cartService.add(str);
        
    }
}

獲取資料
package rmd_cart_provider.service.test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.rmd.cart.bean.SpuInfo;
import com.rmd.cart.service.CartService;

@RunWith(SpringJUnit4ClassRunner.class)  //使用junit4進行測試
@ContextConfiguration({"/applicationContext.xml"}) //載入配置檔案
public class CartTest {


    @Resource  
    private CartService cartService;

    @Test   
    public void test() throws JsonGenerationException, JsonMappingException, IOException{
    	//獲取資料
    	List<SpuInfo> spuList = new ArrayList<>();
    	ObjectMapper om = new ObjectMapper();
    	 //轉回物件
        Set<String> set = cartService.getCart(null);
        
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()) {
            String value = iterator.next();
            SpuInfo spuVo = om.readValue(value, SpuInfo.class);
            spuList.add(spuVo);
        }
        
    }
}

上面新增和獲取資料的時候用到了JUnit4和ObjectMapper

JUnit4單元測試,這個應該都知道,只要加入包就行

        <dependency>
	     <groupId>junit</groupId>
	     <artifactId>junit</artifactId>
	     <version>4.12</version>
	     <scope>test</scope>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-test</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-tx</artifactId>
		<version>${spring.version}</version>
	</dependency>

ObjectMapper這個是一個高效的物件和json之間轉換的類,具體方法查文件,誰用都說好,推薦給大家
<dependency>
         <groupId>org.codehaus.jackson</groupId>
         <artifactId>jackson-mapper-asl</artifactId>
         <version>1.9.4</version>
    	</dependency>

以上是個人在學習和做專案中用到的東西,記錄一下,如有更好的建議一起研究學習