1. 程式人生 > >二 java 中使用redis API編輯基本資料型別

二 java 中使用redis API編輯基本資料型別

package com.ssm.chapter18.main;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.connection.RedisListCommands;
import org.springframework.data.redis.connection.RedisZSetCommands.Limit;
import org.springframework.data.redis.connection.RedisZSetCommands.Range;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;

public class Chapter18Main {

public static void main(String[] args) {
testString();
// testCal();
// testRedisHash();
// testList();
// testBList();
// testSet();
// testZset();
// testHyperLogLog();
}

public static void testString() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);
// 設值
redisTemplate.opsForValue().set("key1", "value1");
redisTemplate.opsForValue().set("key2", "value2");
// 通過key獲取值
String value1 = (String) redisTemplate.opsForValue().get("key1");
System.out.println(value1);
// 通過key刪除值
redisTemplate.delete("key1");
// 求長度
Long length = redisTemplate.opsForValue().size("key2");
System.out.println(length);
// 設值新值並返回舊值
String oldValue2 = (String) redisTemplate.opsForValue().getAndSet("key2", "new_value2");
System.out.println(oldValue2);
// 通過key獲取值.
String value2 = (String) redisTemplate.opsForValue().get("key2");
System.out.println(value2);
// 求子串
String rangeValue2 = redisTemplate.opsForValue().get("key2", 0, 3);
System.out.println(rangeValue2);
// 追加字串到末尾,返回新串長度
int newLen = redisTemplate.opsForValue().append("key2", "_app");
System.out.println(newLen);
String appendValue2 = (String) redisTemplate.opsForValue().get("key2");
System.out.println(appendValue2);
}

/**
* 測試Redis運算.
*/
public static void testCal() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);
redisTemplate.opsForValue().set("i", "9");
printCurrValue(redisTemplate, "i");
redisTemplate.opsForValue().increment("i", 1);
printCurrValue(redisTemplate, "i");
redisTemplate.getConnectionFactory().getConnection().decr(redisTemplate.getKeySerializer().serialize("i"));
printCurrValue(redisTemplate, "i");
redisTemplate.getConnectionFactory().getConnection().decrBy(redisTemplate.getKeySerializer().serialize("i"), 6);
printCurrValue(redisTemplate, "i");
redisTemplate.opsForValue().increment("i", 2.3);
printCurrValue(redisTemplate, "i");
}

/**
* 列印當前key的值
*
* @param redisTemplate
* spring RedisTemplate
* @param key鍵
*/
public static void printCurrValue(RedisTemplate redisTemplate, String key) {
String i = (String) redisTemplate.opsForValue().get(key);
System.err.println(i);
}

public static void testRedisHash() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);
String key = "hash";
Map<String, String> map = new HashMap<String, String>();
map.put("f1", "val1");
map.put("f2", "val2");
// 相當於hmset命令
redisTemplate.opsForHash().putAll(key, map);
// 相當於hset命令
redisTemplate.opsForHash().put(key, "f3", "6");
printValueForhash(redisTemplate, key, "f3");
// 相當於 hexists key filed命令
boolean exists = redisTemplate.opsForHash().hasKey(key, "f3");
System.out.println(exists);
// 相當於hgetall命令
Map keyValMap = redisTemplate.opsForHash().entries(key);
// 相當於hincrby命令
redisTemplate.opsForHash().increment(key, "f3", 2);
printValueForhash(redisTemplate, key, "f3");
// 相當於hincrbyfloat命令
redisTemplate.opsForHash().increment(key, "f3", 0.88);
printValueForhash(redisTemplate, key, "f3");
// 相當於hvals命令
List valueList = redisTemplate.opsForHash().values(key);
// 相當於hkeys命令
Set keyList = redisTemplate.opsForHash().keys(key);
List<String> fieldList = new ArrayList<String>();
fieldList.add("f1");
fieldList.add("f2");
// 相當於hmget命令
List valueList2 = redisTemplate.opsForHash().multiGet(key, keyList);
// 相當於hsetnx命令
boolean success = redisTemplate.opsForHash().putIfAbsent(key, "f4", "val4");
System.out.println(success);
// 相當於hdel命令
Long result = redisTemplate.opsForHash().delete(key, "f1", "f2");
System.out.println(result);
}

private static void printValueForhash(RedisTemplate redisTemplate, String key, String field) {
// 相當於hget命令
Object value = redisTemplate.opsForHash().get(key, field);
System.out.println(value);
}

public static void testList() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);
try {
// 刪除連結串列,以便我們可以反覆測試
redisTemplate.delete("list");
// 把node3插入連結串列list
redisTemplate.opsForList().leftPush("list", "node3");
List<String> nodeList = new ArrayList<String>();
for (int i = 2; i >= 1; i--) {
nodeList.add("node" + i);
}
// 相當於lpush把多個價值從左插入連結串列
redisTemplate.opsForList().leftPushAll("list", nodeList);
// 從右邊插入一個節點
redisTemplate.opsForList().rightPush("list", "node4");
// 獲取下標為0的節點
String node1 = (String) redisTemplate.opsForList().index("list", 0);
// 獲取連結串列長度
long size = redisTemplate.opsForList().size("list");
// 從左邊彈出一個節點
String lpop = (String) redisTemplate.opsForList().leftPop("list");
// 從右邊彈出一個節點
String rpop = (String) redisTemplate.opsForList().rightPop("list");
// 注意,需要使用更為底層的命令才能操作linsert命令
// 使用linsert命令在node2前插入一個節點
redisTemplate.getConnectionFactory().getConnection().lInsert("list".getBytes("utf-8"),
RedisListCommands.Position.BEFORE, "node2".getBytes("utf-8"), "before_node".getBytes("utf-8"));
// 使用linsert命令在node2後插入一個節點
redisTemplate.getConnectionFactory().getConnection().lInsert("list".getBytes("utf-8"),
RedisListCommands.Position.AFTER, "node2".getBytes("utf-8"), "after_node".getBytes("utf-8"));
// 判斷list是否存在,如果存在則從左邊插入head節點
redisTemplate.opsForList().leftPushIfPresent("list", "head");
// 判斷list是否存在,如果存在則從右邊插入end節點
redisTemplate.opsForList().rightPushIfPresent("list", "end");
// 從左到右,或者下標從0到10的節點元素
List valueList = redisTemplate.opsForList().range("list", 0, 10);
nodeList.clear();
for (int i = 1; i <= 3; i++) {
nodeList.add("node");
}
// 在連結串列左邊插入三個值為node的節點
redisTemplate.opsForList().leftPushAll("list", nodeList);
// 從左到右刪除至多三個node節點
redisTemplate.opsForList().remove("list", 3, "node");
// 給連結串列下標為0的節點設定新值
redisTemplate.opsForList().set("list", 0, "new_head_value");
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
// 列印連結串列資料
printList(redisTemplate, "list");
}

public static void printList(RedisTemplate redisTemplate, String key) {
// 連結串列長度
Long size = redisTemplate.opsForList().size(key);
// 獲取整個連結串列的值
List valueList = redisTemplate.opsForList().range(key, 0, size);
// 列印
System.out.println(valueList);
}

public static void testBList() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);
// 清空資料,可以重複測試
redisTemplate.delete("list1");
redisTemplate.delete("list2");
// 初始化連結串列list1
List<String> nodeList = new ArrayList<String>();
for (int i = 1; i <= 5; i++) {
nodeList.add("node" + i);
}
redisTemplate.opsForList().leftPushAll("list1", nodeList);
// Spring使用引數超時時間作為阻塞命令區分,等價於blpop命令,並且可以設定時間引數
redisTemplate.opsForList().leftPop("list1", 1, TimeUnit.SECONDS);
// Spring使用引數超時時間作為阻塞命令區分,等價於brpop命令,並且可以設定時間引數
redisTemplate.opsForList().rightPop("list1", 1, TimeUnit.SECONDS);
nodeList.clear();
// 初始化連結串列list2
for (int i = 1; i <= 3; i++) {
nodeList.add("data" + i);
}
redisTemplate.opsForList().leftPushAll("list2", nodeList);
// 相當於rpoplpush命令,彈出list1最右邊的節點,插入到list2最左邊
redisTemplate.opsForList().rightPopAndLeftPush("list1", "list2");
// 相當於brpoplpush命令,注意在Spring中使用超時引數區分
redisTemplate.opsForList().rightPopAndLeftPush("list1", "list2", 1, TimeUnit.SECONDS);
// 列印連結串列資料
printList(redisTemplate, "list1");
printList(redisTemplate, "list2");
}

public static void testSet() {
// 請把RedisTemplate值序列化器設定為StringRedisSerializer測試該程式碼片段
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);
Set set = null;
// 將元素加入列表
redisTemplate.boundSetOps("set1").add("v1", "v2", "v3", "v4", "v5", "v6");
redisTemplate.boundSetOps("set2").add("v0", "v2", "v4", "v6", "v8");
// 求集合長度
redisTemplate.opsForSet().size("set1");
// 求差集
set = redisTemplate.opsForSet().difference("set1", "set2");
// 求並集
set = redisTemplate.opsForSet().intersect("set1", "set2");
// 判斷是否集合中的元素
boolean exists = redisTemplate.opsForSet().isMember("set1", "v1");
// 獲取集合所有元素
set = redisTemplate.opsForSet().members("set1");
// 從集合中隨機彈出一個元素
String val = (String) redisTemplate.opsForSet().pop("set1");
// 隨機獲取一個集合的元素
val = (String) redisTemplate.opsForSet().randomMember("set1");
// 隨機獲取2個集合的元素
List list = redisTemplate.opsForSet().randomMembers("set1", 2L);
// 刪除一個集合的元素,引數可以是多個
redisTemplate.opsForSet().remove("set1", "v1");
// 求兩個集合的並集
redisTemplate.opsForSet().union("set1", "set2");
// 求兩個集合的差集,並儲存到集合diff_set中
redisTemplate.opsForSet().differenceAndStore("set1", "set2", "diff_set");
// 求兩個集合的交集,並儲存到集合inter_set中
redisTemplate.opsForSet().intersectAndStore("set1", "set2", "inter_set");
// 求兩個集合的並集,並儲存到集合union_set中
redisTemplate.opsForSet().unionAndStore("set1", "set2", "union_set");
}

public static void testZset() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);
// Spring提供介面TypedTuple操作有序集合
Set<TypedTuple> set1 = new HashSet<TypedTuple>();
Set<TypedTuple> set2 = new HashSet<TypedTuple>();
int j = 9;
for (int i = 1; i <= 9; i++) {
j--;
// 計算分數和值
Double score1 = Double.valueOf(i);
String value1 = "x" + i;
Double score2 = Double.valueOf(j);
String value2 = j % 2 == 1 ? "y" + j : "x" + j;
// 使用Spring提供的預設TypedTuple——DefaultTypedTuple
TypedTuple typedTuple1 = new DefaultTypedTuple(value1, score1);
set1.add(typedTuple1);
TypedTuple typedTuple2 = new DefaultTypedTuple(value2, score2);
set2.add(typedTuple2);
}
// 將元素插入有序集合zset1
redisTemplate.opsForZSet().add("zset1", set1);
redisTemplate.opsForZSet().add("zset2", set2);
// 統計總數
Long size = null;
size = redisTemplate.opsForZSet().zCard("zset1");
// 計分數為score,那麼下面的方法就是求3<=score<=6的元素
size = redisTemplate.opsForZSet().count("zset1", 3, 6);
Set set = null;
// 從下標一開始擷取5個元素,但是不返回分數,每一個元素是String
set = redisTemplate.opsForZSet().range("zset1", 1, 5);
printSet(set);
// 擷取集合所有元素,並且對集合按分數排序,並返回分數,每一個元素是TypedTuple
set = redisTemplate.opsForZSet().rangeWithScores("zset1", 0, -1);
printTypedTuple(set);
// 將zset1和zset2兩個集合的交集放入集合inter_zset
size = redisTemplate.opsForZSet().intersectAndStore("zset1", "zset2", "inter_zset");
// 區間
Range range = Range.range();
range.lt("x8");// 小於
range.gt("x1");// 大於
set = redisTemplate.opsForZSet().rangeByLex("zset1", range);
printSet(set);
range.lte("x8");// 小於等於
range.gte("x1");// 大於等於
set = redisTemplate.opsForZSet().rangeByLex("zset1", range);
printSet(set);
// 限制返回個數
Limit limit = Limit.limit();
// 限制返回個數
limit.count(4);
// 限制從第五個開始擷取
limit.offset(5);
// 求區間內的元素,並限制返回4條
set = redisTemplate.opsForZSet().rangeByLex("zset1", range, limit);
printSet(set);
// 求排行,排名第1返回0,第2返回1
Long rank = redisTemplate.opsForZSet().rank("zset1", "x4");
System.err.println("rank = " + rank);
// 刪除元素,返回刪除個數
size = redisTemplate.opsForZSet().remove("zset1", "x5", "x6");
System.err.println("delete = " + size);
// 按照排行刪除從0開始算起,這裡將刪除第排名第2和第3的元素
size = redisTemplate.opsForZSet().removeRange("zset2", 1, 2);
// 獲取所有集合的元素和分數,以-1代表全部元素
set = redisTemplate.opsForZSet().rangeWithScores("zset2", 0, -1);
printTypedTuple(set);
// 刪除指定的元素
size = redisTemplate.opsForZSet().remove("zset2", "y5", "y3");
System.err.println(size);
// 給集合中的一個元素的分數加上11
Double dbl = redisTemplate.opsForZSet().incrementScore("zset1", "x1", 11);
redisTemplate.opsForZSet().removeRangeByScore("zset1", 1, 2);
set = redisTemplate.opsForZSet().reverseRangeWithScores("zset2", 1, 10);
printTypedTuple(set);
}

/**
* 列印TypedTuple集合
*
* @param set
* -- Set<TypedTuple>
*/
public static void printTypedTuple(Set<TypedTuple> set) {
if (set != null && set.isEmpty()) {
return;
}
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
TypedTuple val = (TypedTuple) iterator.next();
System.err.print("{value = " + val.getValue() + ", score = " + val.getScore() + "}\n");
}
}

/**
* 列印普通集合
*
* @param set普通集合
*/
public static void printSet(Set set) {
if (set != null && set.isEmpty()) {
return;
}
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Object val = iterator.next();
System.out.print(val + "\t");
}
System.out.println();
}

public static void testHyperLogLog() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);
redisTemplate.opsForHyperLogLog().add("HyperLogLog", "a", "b", "c", "d", "a");
redisTemplate.opsForHyperLogLog().add("HyperLogLog2", "a");
redisTemplate.opsForHyperLogLog().add("HyperLogLog2", "z");
Long size = redisTemplate.opsForHyperLogLog().size("HyperLogLog");
System.err.println(size);
size = redisTemplate.opsForHyperLogLog().size("HyperLogLog2");
System.err.println(size);
redisTemplate.opsForHyperLogLog().union("des_key", "HyperLogLog", "HyperLogLog2");
size = redisTemplate.opsForHyperLogLog().size("des_key");
System.err.println(size);
}
}