java操作redis簡單示例
初學redis,在java語言和環境下完成redis的入門學習。
首先,官網下載源碼,編譯,安裝,修改配置文件redis.conf中的三項:
1. 註釋掉 bind 127.0.0.1
2. daemonize no 改爲 daemonize yes
3. protected-mode yes 改爲protected-mode no
這樣的話運行 redis-server redis.conf 默認就是在後臺運行的了,而且,允許遠程主機連接。
使用jedis作爲驅動來完成java程序訪問redis服務器,測試代碼如下:
Jedis jedis = new Jedis("192.168.100.103", 6379);
res = jedis.ping();
System.out.println(res);
輸出PONG說明連接成功!
1. 使用redis的list數據結構完成生產者-消費者模型
//Redis Server IP Port
private static String redisServerIP = "192.168.100.103";
private static int redisServerPort = 6379;
//生產者數據存儲隊列
private static String key_src = "task-queue";
private static String key_tmp = "tmp-queue";
public static class Producer implements Runnable{
Jedis jedis = new Jedis(redisServerIP, redisServerPort);
public void run() {
while(true) {
//使用UUID模擬產生了一個任務
String str = UUID.randomUUID().toString();
//加入隊列
jedis.lpush(key_src, str);
System.out.println("插入了一個新任務: " + str + "當前任務總數:" + jedis.llen(key_src));
try {
Random random = new Random();
Thread.sleep(random.nextInt(500) + 500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static class Consumer implements Runnable {
Jedis jedis = new Jedis(redisServerIP, redisServerPort);
public void run() {
while(true) {
//從隊列中取出任務
String taskID = jedis.rpoplpush(key_src, key_tmp );
if (taskID != null) {
//處理任務
//.....
System.out.println("處理一個新任務: " + taskID + "當前任務總數: " + jedis.llen(key_src));
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new Thread(new Producer()).start(); //生產者線程
new Thread(new Consumer()).start(); //消費者線程
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
2. 採用hash結構完成最簡單的購物車模型
private static String redisServerIP = "192.168.100.103";
private static int redisServerPort = 6379;
private static String hash_name = "ShoppingCart";
public static void main(String[] args) {
Jedis jedis = new Jedis(redisServerIP, redisServerPort);
//模擬購物車中的數據
Map<String, String> goodsMap = new HashMap<String, String>();
goodsMap.put("java", "5");
goodsMap.put("C/C++", "3");
goodsMap.put("Node.js", "10");
goodsMap.put("C#", "10");
//hmset命令
jedis.hmset(hash_name, goodsMap);
System.out.println("當前共有 " + jedis.hlen(hash_name) + "個fields");
List<String> fields = new ArrayList<String>();
Set<String> keySet = jedis.hkeys(hash_name);
Iterator i = keySet.iterator();
while (i.hasNext()) {
fields.add(i.next().toString());
}
//hmget命令
List<String> list = jedis.hmget(hash_name, fields.get(0), fields.get(1), fields.get(2));
System.out.println(list);
//hgetall命令
Map<String, String> map = jedis.hgetAll(hash_name);
Set<Entry<String, String>> entrySet = map.entrySet();
for (Entry<String, String> entry: entrySet) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
jedis.disconnect();
}
3. 事物測試
private static String redisServerIP = "192.168.100.103";
private static int redisServerPort = 6379;
public static void main(String[] args) {
Jedis jedis = new Jedis(redisServerIP, redisServerPort);
long start = System.currentTimeMillis();
//開啓事物
Transaction transaction = jedis.multi();
Map<String, String> map = new HashMap<String, String>();
map.put("username", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
map.put("password", "123456");
map.put("age", "25");
map.put("gender", "man");
map.put("email", "[email protected]");
map.put("address", "中國廣東省深圳市");
map.put("tel", "18888888888");
map.put("position", "軟件工程師");
map.put("birth_date", "2016-01-01 00:00:00");
map.put("tel", "2016-01-01 00:00:00");
int totalRecords = 1024;
for (int i = 0; i < totalRecords; i++) {
String key = "user_" + i;
Response<String> result = transaction.hmset(key, map);
}
//提交事物
List<Object> list = transaction.exec();
System.out.println("插入數據量: " + list.size());
long end = System.currentTimeMillis();
System.out.println("總共用時: " + ((end - start)/1000.0) + " seconds");
jedis.disconnect();
}
4. 採用zset完成最熱商品排序功能
private static String redisServerIP = "192.168.100.103";
private static int redisServerPort = 6379;
private static String productTopNKey = "productTopN";
//商品熱搜榜
public static class ProductHotN implements Runnable {
Jedis jedis = new Jedis(redisServerIP, redisServerPort);
//構造熱搜的商品
String[] productTopN = {"iPhone7 Plus", "P9 Plus", "XiaoMi Note", "Vivo X7 Plus", "Galaxy Note7"};
//模擬商搜索次數的變化
public void run() {
while (true) {
Random random = new Random();
//隨機挑一個商品
String product = productTopN[random.nextInt(5)];
//搜索度自增1
jedis.zincrby(productTopNKey, 1, product);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//查看商品熱搜榜
public static class HotViewer implements Runnable {
Jedis jedis = new Jedis(redisServerIP, redisServerPort);
int i = 1;
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("第" + i + "次獲取排行榜");
Set<Tuple> set = jedis.zrevrangeWithScores(productTopNKey, 0, -1);
for (Tuple tuple: set) {
System.out.println(tuple.getElement() + ": " + tuple.getScore());
}
i ++;
}
}
}
public static void main(String[] args) {
new Thread(new ProductHotN()).start();
new Thread(new HotViewer()).start();
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}