java使用jedis操作redis。
名字很好記,redis的r換成j,j即java。
redis-server要做到:
- bind綁定機器的實際ip
- 防火牆開放對應端口
Jedis的使用
1、添加jedis依賴
需要2個jar包:jedis.jar、commons-pool2.jar。
jedis使用apache的線程池,所以需要添加commons-pool2.jar。
使用maven,添加jedis時會自動包含commons-pool2。
github上只有源碼,如果要下載jar包,可以到Maven Repository下載。
2、使用示例
Jedis jedis=new Jedis("192.168.1.9",6379); // jedis.auth("abcd"); //如果需要密碼 //jedis.select(0); //選擇數據庫,下標指定,默認使用db0 if (jedis.ping().equals("PONG")){ //鏈路通暢 jedis.set("name","chy"); System.out.println(jedis.get("name")); } else{ System.out.println("無法連接redis服務器"); } jedis.close();
Jedis jedis=new Jedis("192.168.1.9",6379); if (jedis.ping().equals("PONG")){ //連接成功 jedis.zadd("users", 1223, "zhangsan"); jedis.zadd("users", 2568, "lisi"); jedis.zadd("users", 1379, "wangwu"); //迭代 Set<Tuple> users = jedis.zrangeWithScores("users", 0, -1); //[0,-1] for (Tuple user:users){ String name = user.getElement(); //獲取元素值 double score = user.getScore(); //獲取分數 System.out.println(name+"的積分是:"+score); } } else{ System.out.println("無法連接redis服務器"); } jedis.close();
Jedis類的常用方法
1、構造方法
- Jedis(String host, int port) //指定redis服務器主機地址、端口號,host 可以是ip或者域名。參數均可選,缺省時默認為127.0.0.1、6379
- Jedis(String host,int port, int timeout, boolean ssl) //連接超時時間、是否使用安全連接。參數都可選。
2、連接
- auth(String password) //驗證密碼
- ping() //是否能ping通,能ping通則返回String類型的PONG。
- connect() //連接redis-server。這個很少用,因為進行讀寫操作時會檢測是否已連接,沒連接會自動連接
- close() //關閉連接並釋放資源
- shutdown() //關閉redis-server
3、redis-server的配置項
- configGet(String param) //獲取redis-server配置的某個參數值
- configSet(String param, String value) //設置redis-server的一個配置項
- configRewrite() //同步到配置文件中,永久有效。若不同步,則重啟redis-server失效。
4、數據庫
- select(index db) //選擇要使用的數據庫,默認使用db0
- flushDB() //清空當前數據庫
- flushAll() //清空所有數據庫
- save() //同步到硬盤
- bgsave() //后台同步
5、key
- set(String key,String value) //如果key已存在,會覆蓋
- setnx(String key, String value) //key不存在時才設置,若key已存在,則不進行任何操作
- mset(String key1,String value2,String key2, String value2, .....) //同時設置多個鍵值對
- msetnx(String key1,String value2,String key2, String value2, .....) //key不存在時才設置
- expire(String key, int seconds) //設置過期時間
- setex(String key,int seconds, String value) //設置鍵值對、並指定過期時間,默認永不過期
- get(String key) //返回String類型的value
- mget(String key1,String key2, .....) //同時獲取多個value,返回值是List<String>
- exists(String key) //檢測某個key是否存在
- rename(String oldKey,String newKey) //重命名key
- type(String key) //獲取value的類型,string、hash、list、set、sorted set。
- del(String key1, String key2, ....) //刪除一個或多個鍵值對
- incr(String key) //值自增,+1,返回操作后的值,long型
- incrBy(String key, long increment) //指定int型增量,返回long
- incrByFloat(String key,double increment) //指定double型增量,返回double。方法名中的float表示浮點數,並不限於單精度
- decr(String key) //值自減
- decrBy(String key,long decrement) //原值減去decrement,decrement要指定為正數
沒有decrByFloat()方法,可以用incrByFloat(),增量指定為負數即可。
6、hash
- hset(String key, String field, String value) //設置單個字段
- hsetnx(String key, String field, String value)
- hset(String key, Map<String ,String> map) //把map中的字段都添加進來
- hget(String key , String field)
- hmget(String key, String field1, String field2, ....) //獲取多個字段的值,返回List<String>
- hgetAll(String key) //獲取所有的字段,返回Map<String , String >
- hexists(String key, String field) //某個字段是否存在
- hdel(String key, String field) //刪除某個字段
- hlen(String key) //返回該hash表中字段數,返回值是Long型
- hkeys(String key) //獲取所有的字段名,返回值是Set<String>
- hvals(String key) //獲取所有的字段值,返回值是List<String>
- hincrBy(String key, String field, long increment) //返回操作后的數值,long型
- hincrByFloat(String key, String field , double increment) //double
沒有hdecrXxx()方法,將上面的增量寫成負數即可。
7、list
- lpush(String key, String element1, String element2, .....) //在列表頭插入一個或多個元素
- lpushx(String key, String element1, String element2 ,.....) //key存在才插入,若key不存在,不進行任何操作
- lpop(String key) //彈出列表的第一個元素。彈出是指刪除並返回。
- rpush(String key, String element1, String element2, ....) //在列表尾插入一個或多個元素
- rpushx(String key, String element1, String element2, ....)
- rpop(String key) //彈出列表的最后一個元素
- lindex(String key, long index) //返回指定位置上的元素
- linsert(String key,ListPosition position,,String element1, String element2) //在element1的前面|后面插入element2。第二個參數是枚舉類型,可用的值:ListPosition.BEFORE,ListPosition.AFTER
- llen(String key) //元素個數,long
- lrange(String key, long startIndex, long endIndex) //返回[startIndex, endIndex]上的所有元素,List<String>
- lset(String key, long index, String element) //修改該位置上的值,index上要已有元素。
- lrem(String key, long count, String element) //從列表中移除count個值是value的元素,count為正表示從前往后搜索,為負表示從后往前搜索
- ltrim(String key, long startIndex, long endIndex) //修剪列表,只保留[startIndex, endIndex]上的元素,其余刪除。返回String類型的操作結果,“OK”表示操作成功。
8、set
- sadd(String key, String element1, String element2, ....) //添加一個或多個元素
- srem(String key, String element1, String element2, ...) //移除一個或多個元素
- smembers(String key) //返回集合中所有的元素,Set<String>
- scard(String key) //返回集合中的元素個數,long
- sismember(String key, String element) //檢測集合中是否包含某個元素,boolean
- spop(String key) //隨機彈出一個元素,String
- spop(String key, long count) //隨機彈出count個元素,Set<String>
- srandmember(String key) //隨機返回一個元素。與spop()的區別是,srandmember()不會移除該元素
- srandmember(Sring key, long count)
- sdiff(String key1, String key2, ....) //求差集,返回Set<String>
- sdiffstore(String destKey, String key1, String key2) //把差集中的元素存儲到destKey集合中,返回差集中的元素個數,long
相同用法的還有:
- sinter 交集
- sunion 並集
set是無序的,沒有與索引相關的方法。
9、sorted set
- zadd(String key, doubel score, String element)
- zadd(String key, Map<String, Double> map)
- zrem(String key, String element1, String element2, ....) //移除一個或多個元素
- zcard(String key) //元素個數,long
- zcount(String key, double minScore, double maxScore) //返回[minScore, maxScore]區間上的元素個數。元素默認按score升序排列
- zcount(String key, String startElement, String endElement) //返回[startElement, endElement]上的元素個數
- zrank(String key, String element) //返回該元素所在位置|排名,下標。默認按score升序排列
- zrevrank(String key, String element) //按score降序排列
- zincrby(String key, double increment, String element) //返回操作后的元素值,double。沒有zdecrby()方法,將增量設置為負數即可
- zinter(String destKey, String...keys) //交集,結果存儲到destKey集合中
- zunion(String destKey,String...keys) //並集
- zrangeByXxx() 系列方法 //返回該某個區間上的所有元素,Set<String>。默認按score升序排列
- zrevrangeXxx() 系列方法 //返回某個區間上的所有元素,Set<String>。按score降序排列,rev即reverse,反序
- zremrangeByXxx() 系列方法 //刪除某個區間上的所有元素
list返回多個元素時用的是List,set、sorted set返回多個元素時用的是Set,hash返回多個值時用的是Map、List、Set。
JedisPool的使用
自動創建一些Jedis對象,放在JedisPool中,要用時取出來直接用即可,用完放回池中,減少創建Jedis對象的時間開銷。
JedisPool jedisPool = new JedisPool("192.168.1.9",6379); //host、port均可選,缺省時使用默認值 Jedis jedis = jedisPool.getResource();
可以對JedisPool進行配置:
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(15); jedisPoolConfig.setMaxIdle(10); jedisPoolConfig.setMinIdle(5); jedisPoolConfig.setMaxWaitMillis(180);//若一個Jedis對象閑置多少秒,就銷毀 JedisPool jedisPool= new JedisPool(jedisPoolConfig, "192.168.1.9", 6379); Jedis jedis = jedisPool.getResource();
JedisPool jedisPool= new JedisPool(jedisPoolConfig, "192.168.1.9", 6379, 30, "abcd", true);
配置、host、port、超時時間、密碼、是否使用ssl,參數均可選。
超時時間是指多少秒內連不上redis-server就返回失敗。
如果要使用ssl,需要在Linux上安裝ssl證書。
連接redis集群
// 集群節點 Set<HostAndPort> nodes = new HashSet(); nodes.add(new HostAndPort("192.168.1.7", 6379)); //host、port nodes.add(new HostAndPort("192.168.1.7", 6380)); nodes.add(new HostAndPort("192.168.1.7", 6381)); nodes.add(new HostAndPort("192.168.1.7", 6382)); nodes.add(new HostAndPort("192.168.1.7", 6383)); nodes.add(new HostAndPort("192.168.1.7", 6384));
//獲取JedisCluster對象 JedisCluster jedisCluster = new JedisCluster(nodes);
jedisCluster.set("level", "master"); String level = jedisCluster.get("level"); System.out.println("your level is : "+level); jedisCluster.zadd("users", 1223, "zhangsan"); jedisCluster.zadd("users", 2568, "lisi"); jedisCluster.zadd("users", 1379, "wangwu"); Set<Tuple> users = jedisCluster.zrangeWithScores("users", 0, -1); //[0,-1] for (Tuple user:users){ String name = user.getElement(); //獲取元素值 double score = user.getScore(); //獲取分數 System.out.println(name+"的積分是:"+score); }
JedisCluster類的方法和Jedis類的方法基本一樣,不再一一說明。