In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "the introduction and application of Redis". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn the introduction and application of Redis.
I can't get off the official website. I found this address here. The version is relatively old.
Download the driver and search for jedis
Referenc
Basic operation
Public class RedisTest {public static void main (String [] args) {/ * address port timeout * / Jedis jedis = new Jedis ("localhost", 6379, 100000) / * Test whether / System.out.println is connected ("Service is running:" + jedis.ping ()) / * set: set key value * get: get key value * del: delete key * append: append key value * incr:key value increases 1 * incrBy:key value increases itself Specify step size * decr:key value minus 1 * decrBy:key value self-decrease, specify step size * expire: set expiration time (seconds) * setex: set key value, specify survival time (seconds) * setnx: set key value. It will be set only if key does not exist. If key exists, the operation will be rolled back. The result returns 0, which means the * ttl:time to live has not been set successfully. Get the survival time of key (in seconds).-1 means never expire. * persist: remove the expire setting of key. No more expiration time * / jedis.set ("first", "Hello World!") System.out.println (jedis.get ("first")) / * LIST * can realize the function of queue * lpush: insert multiple elements from the head of the list * rpush: insert multiple elements from the end of the list * llen: return the number of elements in the list * lpop: remove and return the first element of list from the header of the list * lrem: start with the header Delete n values * lrange: get a subset of the specified range from the list * / jedis.del ("list") Jedis.lpush ("list", "1", "2", "3"); jedis.lpush ("list", "4"); Long count=jedis.llen ("list"); List list=jedis.lrange ("list", 0, count); System.out.println (list.toString ()) / * sadd: add a value to the set object * smembers: get all the values in set * sismember: determine whether a value exists in set * srandmember: get a value randomly from set * srem: delete a value from set * scard: return the number of item of set * / 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: sets the key value. The value type is map object * type: the type that returns the key value. Possible values include none, string, hash, set, list Zset * hkeys: get all key * hvals: get the corresponding values of all key * hmget: get the values of multiple field at once * hexists: determine whether the field exists * hset: set the value of field * hgetAll: get all the content * hget: get the field value * hdel: delete field * hincrBy:field value increase by 1 * hlen: calculate the number of field * hsetnx: set the key value. The field will be set only if it does not exist. If the field exists, the operation will be rolled back. The result will return 0, indicating that the setting is not successful. Can be used to implement distributed locks * / 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);}}
Message subscriptions,
Subscribe to public class Consumer {public static void main (String [] args) {/ * address port timeout * / Jedis jedis = new Jedis ("localhost", 6379, 100000) / * message subscription * / 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*") }} / / publish jedis.publish ("test1", "message from test1"); jedis.publish ("test2", "message from test2")
Redis distributed lock
Public class RedisTool {private static final String LOCK_SUCCESS = "OK"; private static final Long RELEASE_SUCCESS = 1L / * attempt to acquire distributed lock * @ param jedis Redis client * @ param lockKey lock * @ param requestId request identification * @ param expireTime timeout * @ return whether to obtain successful * / 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 } / * release distributed lock * @ param jedis Redis client * @ param lockKey lock * @ param requestId request identification * @ return whether the release was successful * / 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 () + "acquire lock") Try {Thread.sleep (1000L);} catch (InterruptedException e) {e.printStackTrace () } Boolean unlock = RedisTool.releaseDistributedLock (jedis, "lock", uuid) If (unlock) {System.out.println (Thread.currentThread (). GetName () + "release lock"); break }} if (tryCount 0) {System.out.println ("- add goods: "+ key +" quantity: "+ I +"-- ") / / get values String count = jedis.get (key); System.out.println ("remaining inventory:" + count); if (null = = count | | Integer.valueOf (count) 0) {jedis.decr (key) Count = jedis.get (key); System.out.println ("surplus inventory:" + 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; iTunes +) {Thread td = new Thread (rn) Td.start ();} LockSupport.park ();}} at this point, I believe you have a deeper understanding of "the introduction and application of Redis". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.