1. 程式人生 > >redis 系列(七) redis API使用

redis 系列(七) redis API使用

Jedis

redis單機版  java API 操作 

package bhz.redis01;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import redis.clients.jedis.*;
import java.util.*;
 
public class TestSingleRedis {
 
    private static Jedis jedis;		//單例項[]
    private static ShardedJedis shard;		//分片[]
    private static ShardedJedisPool pool;	//池化[apache common - pool2]
 
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    	//單個節點
    	jedis = new Jedis("192.168.1.115", 6379);
    	//分片
        List<JedisShardInfo> shards = Arrays.asList(
                new JedisShardInfo("192.168.1.115",6379)); 
        
        shard = new ShardedJedis(shards);
        //池化
        GenericObjectPoolConfig goConfig = new GenericObjectPoolConfig();
        goConfig.setMaxTotal(100);
        goConfig.setMaxIdle(20);
        goConfig.setMaxWaitMillis(-1);
        goConfig.setTestOnBorrow(true);        
        pool = new ShardedJedisPool(goConfig, shards);
    }
 
    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        jedis.disconnect();
        shard.disconnect();
        pool.destroy();
    }
 
    @Test
    public void testString() {
        //-----新增資料----------  
        jedis.set("name","bhz");//向key-->name中放入了value-->xinxin  
        System.out.println(jedis.get("name"));//執行結果:xinxin  
        
        jedis.append("name", " is my lover"); //拼接
        System.out.println(jedis.get("name")); 
        
        jedis.del("name");  //刪除某個鍵
        System.out.println(jedis.get("name"));
        //設定多個鍵值對
        jedis.mset("name","bhz","age","27","qq","174754613");
        jedis.incr("age"); //進行加1操作
        System.out.println(jedis.get("name") + "-" + jedis.get("age") + "-" + jedis.get("qq"));
    }
    
    /**
     * redis操作Map
     */
    @Test
    public void testMap() {
        //-----新增資料----------  
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", "xinxin");
        map.put("age", "22");
        map.put("qq", "123456");
        jedis.hmset("user",map);
        //取出user中的name,執行結果:[minxr]-->注意結果是一個泛型的List  
        //第一個引數是存入redis中map物件的key,後面跟的是放入map中的物件的key,後面的key可以跟多個,是可變引數  
        List<String> rsmap = jedis.hmget("user", "name", "age", "qq");
        System.out.println(rsmap);  
        //刪除map中的某個鍵值  
        jedis.hdel("user","age");
        System.out.println(jedis.hmget("user", "age")); //因為刪除了,所以返回的是null  
        System.out.println(jedis.hlen("user")); //返回key為user的鍵中存放的值的個數2 
        System.out.println(jedis.exists("user"));//是否存在key為user的記錄 返回true  
        System.out.println(jedis.hkeys("user"));//返回map物件中的所有key  
        System.out.println(jedis.hvals("user"));//返回map物件中的所有value 
  
        Iterator<String> iter=jedis.hkeys("user").iterator();  
        while (iter.hasNext()){  
            String key = iter.next();  
            System.out.println(key+":"+jedis.hmget("user",key));  
        }  
    }
    
    /** 
     * jedis操作List 
     */  
    @Test  
    public void testList(){  
        //開始前,先移除所有的內容  
        jedis.del("java framework");  
        System.out.println(jedis.lrange("java framework",0,-1));  
        //先向key java framework中存放三條資料  
        jedis.lpush("java framework","spring");  
        jedis.lpush("java framework","struts");  
        jedis.lpush("java framework","hibernate");  //mybatis jdbctemplate (spring data [jpa])
        //再取出所有資料jedis.lrange是按範圍取出,  
        // 第一個是key,第二個是起始位置,第三個是結束位置,jedis.llen獲取長度 -1表示取得所有  
        System.out.println(jedis.lrange("java framework",0,-1));  
        
        jedis.del("java framework");
        jedis.rpush("java framework","spring");  
        jedis.rpush("java framework","struts");  
        jedis.rpush("java framework","hibernate"); 
        System.out.println(jedis.lrange("java framework",0,-1));
    }  
    
    /** 
     * jedis操作Set 
     */  
    @Test  
    public void testSet(){  
        //新增  
        jedis.sadd("user1","liuling");  
        jedis.sadd("user1","xinxin");  
        jedis.sadd("user1","ling");  
        jedis.sadd("user1","zhangxinxin");
        jedis.sadd("user1","who");  
        //移除noname  
        jedis.srem("user1","who");  
        System.out.println(jedis.smembers("user1"));//獲取所有加入的value  
        System.out.println(jedis.sismember("user1", "who"));//判斷 who 是否是user集合的元素  
        System.out.println(jedis.srandmember("user1"));  
        System.out.println(jedis.scard("user1"));//返回集合的元素個數  
    } 
    
    @Test  
    public void testRLpush() throws InterruptedException {  
        //jedis 排序  
        //注意,此處的rpush和lpush是List的操作。是一個雙向連結串列(但從表現來看的)  
        jedis.del("a");//先清除資料,再加入資料進行測試  
        jedis.rpush("a", "1");  
        jedis.lpush("a","6");  
        jedis.lpush("a","3");  
        jedis.lpush("a","9");  
        System.out.println(jedis.lrange("a",0,-1));// [9, 3, 6, 1]  
        System.out.println(jedis.sort("a")); //[1, 3, 6, 9]  //輸入排序後結果  
        System.out.println(jedis.lrange("a",0,-1));  
    }  
 
    @Test
    public void testTrans() {
        long start = System.currentTimeMillis();
        Transaction tx = jedis.multi();
        for (int i = 0; i < 1000; i++) {
            tx.set("t" + i, "t" + i);
        }
        //System.out.println(tx.get("t1000").get());
 
        List<Object> results = tx.exec();
        long end = System.currentTimeMillis();
        System.out.println("Transaction SET: " + ((end - start)/1000.0) + " seconds");
    }
 
    @Test
    public void testPipelined() {
        Pipeline pipeline = jedis.pipelined();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            pipeline.set("p" + i, "p" + i);
        }
        //System.out.println(pipeline.get("p1000").get());
        List<Object> results = pipeline.syncAndReturnAll();
        long end = System.currentTimeMillis();
        System.out.println("Pipelined SET: " + ((end - start)/1000.0) + " seconds");
    }
 
    @Test
    public void testPipelineTrans() {
        long start = System.currentTimeMillis();
        Pipeline pipeline = jedis.pipelined();
        pipeline.multi();
        for (int i = 0; i < 100000; i++) {
            pipeline.set("" + i, "" + i);
        }
        pipeline.exec();
        List<Object> results = pipeline.syncAndReturnAll();
        long end = System.currentTimeMillis();
        System.out.println("Pipelined transaction SET: " + ((end - start)/1000.0) + " seconds");
    }
 
    @Test
    public void testShard() {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            String result = shard.set("shard" + i, "n" + i);
        }
        long end = System.currentTimeMillis();
        System.out.println("shard SET: " + ((end - start)/1000.0) + " seconds");
    }
 
    @Test
    public void testShardpipelined() {
        ShardedJedisPipeline pipeline = shard.pipelined();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            pipeline.set("sp" + i, "p" + i);
        }
        List<Object> results = pipeline.syncAndReturnAll();
        long end = System.currentTimeMillis();
        System.out.println("shardPipelined SET: " + ((end - start)/1000.0) + " seconds");
    }
 
    @Test
    public void testShardPool() {
        ShardedJedis sj = pool.getResource();
 
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            String result = sj.set("spn" + i, "n" + i);
        }
        long end = System.currentTimeMillis();
        pool.returnResourceObject(sj);
        System.out.println("shardPool SET: " + ((end - start)/1000.0) + " seconds");
    }
    
    /**
     * <B>方法名稱:</B>Redis使用Lua執行應用程式<BR>
     * <B>概要說明:</B>
     * 我們可以使用Redis+Lua的方式,實現一個完整的事務、保證事務的原子性。
     * 如何使用Redis+Lua?
     * 我們使用scriptLoad方法,把我們寫好的lua指令碼載入到Redis的記憶體中(注意是記憶體,每次重啟則失效)。
     * scriptLoad方法會返回一個索引Key,我們只需要通過這個索引Key就可以找到我們之前放到Redis裡的指令碼。
     * 呼叫evalsha方法,傳入索引key,以及操作鍵、引數值。進行返回 <BR>
     */
    /**
     * lua script:
	 *		local t1 = redis.call('hgetall',KEYS[1]);
	 *		if type(t1) == 'table' then 
	 *			return t1;
	 *		end;
     */
    public static final String SCRIPT = 
    		"local t1 = redis.call('hgetall',KEYS[1]);" + "\n" +
    		"if type(t1) == 'table' then" + "\n" +
    		"return t1;" + "\n" +
    		"end;" + "\n" ;
    @Test
    public void  testLua(){
    	String shakey = jedis.scriptLoad(SCRIPT);//載入指令碼,獲取sha索引 
    	System.out.println("shakey: " + shakey);
    	//要獲取的key值
    	List<String> keys = new ArrayList<>();
    	keys.add("myhash");
    	//傳入的引數
    	List<String> args = new ArrayList<>();
    	// /usr/local/bin/redis-cli -h 192.168.1.115 -p 6379 --eval /usr/local/luadir/03.lua name age , baihezhuo
    	List<String> ret = (List<String>)jedis.evalsha(shakey, keys, args);
    	
    	System.out.println(ret);
    	jedis.close();
    }
   
    
    
    
    
    
 
}