本篇內(nèi)容主要講解“redis的介紹及應(yīng)用”,感興趣的朋友不妨來看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Redis的介紹及應(yīng)用”吧!
成都創(chuàng)新互聯(lián)專注于云和企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站,商城網(wǎng)站建設(shè)。云和網(wǎng)站建設(shè)公司,為云和等地區(qū)提供建站服務(wù)。全流程按需網(wǎng)站策劃,專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,成都創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)
官網(wǎng)下不了,這里找了這個(gè)地址,版本比較老
下載驅(qū)動(dòng),搜索jedis
參考
基本操作
public class RedisTest { public static void main(String[] args) { /** * 地址 端口 超時(shí)時(shí)間 */ Jedis jedis = new Jedis("localhost", 6379, 100000); /** * 測(cè)試是否通 */ System.out.println("服務(wù)正在運(yùn)行: "+jedis.ping()); /** * set:設(shè)置key值 * get:獲取key值 * del:刪除key * append:追加key值 * incr:key值自增1 * incrBy:key值自增,指定步長(zhǎng) * decr:key值自減1 * decrBy:key值自減,指定步長(zhǎng) * expire:為key設(shè)置過期時(shí)間(秒數(shù)) * setex:設(shè)置key值,可指定存活時(shí)間(秒數(shù)) * setnx:設(shè)置key值。key不存在才會(huì)設(shè)置,如果key存在則回滾操作,結(jié)果返回0,表示沒有設(shè)置成功 * ttl:time to live,獲取key的存活時(shí)間(秒),-1表示永不過期 * persist:去掉key的expire設(shè)置,不再有失效時(shí)間 */ jedis.set("first", "Hello World!"); System.out.println(jedis.get("first")); /** * LIST * 可以實(shí)現(xiàn)隊(duì)列的功能 * lpush: 從列表頭部插入多個(gè)元素 * rpush:從列表尾部插入多個(gè)元素 * llen:返回列表中的元素的數(shù)量 * lpop:從列表頭部移除并返回list的第一個(gè)元素 * lrem:從頭部開始找,刪除n個(gè)值 * lrange:從列表中獲取指定范圍的子集 */ jedis.del("list"); jedis.lpush("list", "1","2","3"); jedis.lpush("list", "4"); Long count=jedis.llen("list"); Listlist=jedis.lrange("list", 0, count); System.out.println(list.toString()); /** * sadd:往set對(duì)象中添加一個(gè)值 * smembers:取得set中所有的值 * sismember:判斷一個(gè)值是否在set中存在 * srandmember:從set中隨機(jī)取得一個(gè)值 * srem:從set中刪除一個(gè)值 * scard:返回set的item個(gè)數(shù) */ jedis.del("set"); jedis.sadd("set", "1","2","3"); jedis.sadd("set", "4"); jedis.sadd("set", "4"); Set set=jedis.smembers("set"); System.out.println(set.toString()); /** * hmset:設(shè)置key值,值類型為map對(duì)象 * type:返回key值的類型,可能值有none, string, hash, set, list, zset * hkeys:獲取所有key * hvals:獲取所有key對(duì)應(yīng)的值 * hmget:一次性獲取多個(gè)field的值 * hexists:判斷field是否存在 * hset:設(shè)置field的值 * hgetAll:獲取全部?jī)?nèi)容 * hget:獲取field的值 * hdel:刪除field * hincrBy:field值自增1 * hlen:計(jì)算field的數(shù)目 * hsetnx:設(shè)置key值。field不存在才會(huì)設(shè)置,如果field存在則回滾操作,結(jié)果返回0,表示沒有設(shè)置成功??梢杂脕韺?shí)現(xiàn)分布式鎖 */ jedis.del("user"); Map map = new HashMap (); map.put("name", "cjm"); map.put("age", "33"); map.put("qq", "123456"); jedis.hmset("user", map); System.out.println("type: " + jedis.type("user")); System.out.println("hkeys: " + jedis.hkeys("user")); System.out.println("hvals: " + jedis.hvals("user")); System.out.println("hmget: " + jedis.hmget("user", "name", "age")); System.out.println("hexists: " + jedis.hexists("user", "name")); jedis.hset("user", "pwd", "123"); System.out.println("hgetAll: " + jedis.hgetAll("user")); System.out.println("hget: " + jedis.hget("user", "pwd")); jedis.hdel("user", "qq"); System.out.println("hincrBy: " + jedis.hincrBy("user", "count", 1)); System.out.println("hlen: " + jedis.hlen("user")); Long r = jedis.hsetnx("user", "pwd2", "456"); System.out.println(r); } }
消息訂閱、
訂閱 public class Consumer { public static void main(String[] args) { /** * 地址 端口 超時(shí)時(shí)間 */ Jedis jedis = new Jedis("localhost", 6379, 100000); /** * 消息訂閱 */ JedisPubSub jps=new JedisPubSub() { public void onPMessage(String pattern, String channel, String message) { System.out.println("onPMessage()," + pattern + "=" + channel + "=" + message); } public void onMessage(String channel, String message) { System.out.println("onMessage()," + channel + "=" + message); } }; jedis.psubscribe(jps, "test*"); } } //發(fā)布 jedis.publish("test1", "message from test1"); jedis.publish("test2", "message from test2");
redis分布式鎖
public class RedisTool { private static final String LOCK_SUCCESS = "OK"; private static final Long RELEASE_SUCCESS = 1L; /** * 嘗試獲取分布式鎖 * @param jedis Redis客戶端 * @param lockKey 鎖 * @param requestId 請(qǐng)求標(biāo)識(shí) * @param expireTime 超期時(shí)間 * @return 是否獲取成功 */ public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) { String result = jedis.set(lockKey, requestId,new SetParams().nx().ex(expireTime)); if (LOCK_SUCCESS.equals(result)) { return true; } return false; } /** * 釋放分布式鎖 * @param jedis Redis客戶端 * @param lockKey 鎖 * @param requestId 請(qǐng)求標(biāo)識(shí) * @return 是否釋放成功 */ public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) { String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId)); if (RELEASE_SUCCESS.equals(result)) { return true; } return false; } } public class LockTest { public static void main(String[] args) { Runnable rn = new Runnable() { @Override public void run() { Jedis jedis = new Jedis("localhost", 6379, 100000); String uuid = UUID.randomUUID().toString().replaceAll("-", ""); int tryCount=5; while (true) { Boolean lock = RedisTool.tryGetDistributedLock(jedis, "lock", uuid, 10); if (lock) { System.out.println(Thread.currentThread().getName() + "獲取鎖"); try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } Boolean unlock = RedisTool.releaseDistributedLock(jedis, "lock", uuid); if (unlock) { System.out.println(Thread.currentThread().getName() + "釋放鎖"); break; } } if(tryCount<0) { break; }else { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "嘗試次數(shù):"+tryCount); tryCount--; } } } }; for (int i = 0; i < 20; i++) { Thread t = new Thread(rn); t.start(); } LockSupport.park(); } }
鎖測(cè)試
package com.redis; import java.util.UUID; import java.util.concurrent.locks.LockSupport; import redis.clients.jedis.Jedis; public class ProductServer { /** * 向服務(wù)端添加貨 * * @return */ public boolean addProduct(Jedis jedis, String key, int i) { System.out.println("貨物:" + key + "添加庫存:" + i); if (i > 0) { System.out.println("---添加貨物:" + key + "數(shù)量:" + i + "---"); // 獲取值 String count = jedis.get(key); System.out.println("剩余庫存:" + count); if (null == count || Integer.valueOf(count) <= 0) { System.out.println("---當(dāng)前貨物:" + key + "數(shù)量已銷售完畢"); System.out.println("---當(dāng)前貨物:" + key + "添加開始"); jedis.set(key, i + ""); System.out.println("---當(dāng)前貨物:" + key + "添加結(jié)束"); return true; } } return false; } /** * 消費(fèi)數(shù)據(jù) */ public boolean decryProduct(Jedis jedis, String key, String requestID) { try { Boolean lock = RedisTool.tryGetDistributedLock(jedis, "lock", requestID, 100); if (!lock) { System.out.println("請(qǐng)稍后重試..."); return false; } System.out.println("貨物:" + key + "線程:" + Thread.currentThread().getName() + "消費(fèi)數(shù)據(jù):" + requestID); String count = jedis.get(key); if (null != count && Integer.valueOf(count) > 0) { jedis.decr(key); count = jedis.get(key); System.out.println("剩余庫存:" + count); return true; } } catch (Exception e) { } finally { RedisTool.releaseDistributedLock(jedis, "lock", requestID); } return false; } public static void main(String[] args) { Jedis jedis = new Jedis("localhost", 6379, 10000); ProductServer ps = new ProductServer(); ps.addProduct(jedis, "shouji", 10); Runnable rn = new Runnable() { @Override public void run() { String uuid = UUID.randomUUID().toString().replaceAll("-", ""); Jedis jedis = new Jedis("localhost", 6379, 10000); ps.decryProduct(jedis, "shouji", uuid); } }; for (int i = 0; i < 15; i++) { Thread td = new Thread(rn); td.start(); } LockSupport.park(); } }
到此,相信大家對(duì)“Redis的介紹及應(yīng)用”有了更深的了解,不妨來實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!