Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What api does redis have?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail what api there are in redis. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

1. Introduction of Redis Client

1.1. Introduction

Jedis Client is a client for java recommended by Redis official website, and the library file encapsulates and calls all kinds of API.

Jedis source code project address: https://github.com/xetorthio/jedis

1.2, use

It is best to choose the version corresponding to the server side of Redis Client. In this example, you can use the Redis 2.8.19 client to add the following references using the jedis-2.6.3 Magi Maven project.

Redis.clients jedis 2.6.3 jar compile

1.3. Points for attention

Redis Client has many docking versions. This project currently uses Jedis to officially recommend Java interfacing clients based on its good version support for Redis and API interfacing, and try to avoid using obsolete APIs in coding.

Redis is currently in the transition period of the new version, and version 3.0 is not stable for the time being. However, since version 3.0 provides the latest clustering features, it may be upgraded to 3.0 after the stable version is released in the future. The current version of Jedis in use supports API of 3.0.

2. API commonly used in Redis Client

2.1. Environmental requirements

Language: Java

JDK:1.7

Redis: 2.8.19 (stable version)

2.2, system use

2.2.1. Establish a connection

Ordinary connection

Jedis jedis = new Jedis ("localhost"); jedis.set ("foo", "bar"); String value = jedis.get ("foo"); System.out.println (value)

Set connection pool configuration

The method is used to obtain the connection pool configuration used by redis connection pooling. The connection pool configuration can also be configured by spring injection. The connection pool is managed by org.apache.commons.pool2.impl.GenericObjectPoolConfig, which is commonly used.

The configuration file is as follows

# redis server ip # redis.ip=172.30.5.117 # redis server port number # redis.port=6379 # jedis##pool##config### # jedis maximum allocation object # jedis.pool.maxActive=1024 # jedis maximum number of idel state objects # jedis.pool.maxIdle=200 # jedis pool when no object is returned Maximum waiting time # jedis.pool.maxWait=1000 # jedis when calling the borrowObject method, whether to effectively check whether the # jedis.pool.testOnBorrow=true # jedis calls the returnObject method, whether it effectively checks the # jedis.pool.testOnReturn=true

Connection pool configuration instantiation code (which can also be configured through spring injection):

/ * * acquired connection pool configuration * @ return JedisPoolConfig * * / private JedisPoolConfig getPoolConfig () {if (config = = null) {config = new JedisPoolConfig (); / / maximum number of connections config.setMaxTotal (Integer.valueOf (getResourceBundle (). GetString ("redis.pool.maxTotal")); / / maximum number of idle connections config.setMaxIdle (Integer.valueOf (getResourceBundle (). GetString ("redis.pool.maxIdle") / / get the maximum number of milliseconds to wait for a connection (if set to BlockWhenExhausted when blocking), throw an exception if the timeout is less than zero: blocking uncertain time, default-1config.setMaxWaitMillis (Long.valueOf (getResourceBundle (). GetString ("redis.pool.maxWaitMillis") / / check the validity when getting the connection. Default falseconfig.setTestOnBorrow (Boolean.valueOf (getResourceBundle (). GetString ("redis.pool.testOnBorrow")); / / check the validity when getting the returned result. Default falseconfig.setTestOnReturn (Boolean.valueOf (getResourceBundle (). GetString ("redis.pool.testOnReturn"));} return config;}

Ordinary connection pool connection

What is shown here is a common connection pool method for linking redis, which is similar to the operation of ordinary database connection pooling. / * initialize JedisPool * * / private void initJedisPool () {if (pool = = null) {/ / get the server IP address String ipStr = getResourceBundle () .getString ("redis.ip"); / / get the server port int portStr = Integer.valueOf (getResourceBundle () .server ("redis.port")) / / initialize connection pool pool = new JedisPool (getPoolConfig (), ipStr,portStr);}}

Sentinel connection pool connection

The connection pool is used to deal with the master-slave switching mechanism of Redis's Sentinel, and can correctly get the correct server connection when the server downtime causes the server to switch. When the server adopts this deployment strategy, it is recommended to use this connection pool for operation.

Private void initJedisSentinelPool () {if (sentinelpool = = null) {/ / listener list Set sentinels = new HashSet (); / / listener 1 sentinels.add (new HostAndPort ("192.168.50.236", 26379). ToString (); / / listener 2 sentinels.add (new HostAndPort ("192.168.50.237", 26379). ToString ()) / / configure it in properties for actual use: redis.sentinel.hostandports=192.168.50.236:26379192.168.50.237:26379getResourceBundle () .getString ("redis.sentinel.hostandports") / / mastername is the name of the master on the server Configure in the sentinel.conf of the master server: / / [sentinel monitor server-1M 192.168.50.236 6379 2] / / the server-1M in the middle is masterName String masterName = getResourceBundle () .getString ("redis.sentinel.masterName") / / initialize connection pool sentinelpool = new JedisSentinelPool (masterName,sentinels, getPoolConfig ());}}

ShardedJedisPool connection pool sharding connection

/ * initialize ShardedJedisPool * Redis. Disaster recovery processing can be achieved by configuring Master-Slave mode on the server. * for distributed clusters, consistent hash distributed storage, that is, key sharding storage, can only be achieved through client tools. * Redis may support server-side distributed storage in version 3.0 * * / private void initShardedJedisPool () {if (shardPool = = null) {/ / create multiple redis sharing services String redis1Ip = getResourceBundle (). GetString ("redis1.ip"); int redis1Port = Integer.valueOf (bundle.getString ("redis.port")); JedisShardInfo jedisShardInfo1 = new JedisShardInfo (redis1Ip, redis1Port) String redis2Ip = getResourceBundle (). GetString ("redis2.ip"); int redis2Port = Integer.valueOf (bundle.getString ("redis.port")); JedisShardInfo jedisShardInfo2 = new JedisShardInfo (redis2Ip, redis2Port); List serverlist = new LinkedList (); serverlist.add (jedisShardInfo1); serverlist.add (jedisShardInfo2); / / initialize the connection pool shardPool = new ShardedJedisPool (getPoolConfig (), serverlist);}}

Read-write delete operation

/ / get a Jedis object from the pool Jedis jedis = sentinelpool.getSentinelpoolResource (); String keys = "name"; / / delete the key-value object, and ignore this operation jedis.del (keys) if key does not exist; / / store data jedis.set (keys, "snowolf"); / / determine whether key exists, return false does not exist return true jedis.exists (keys) / / fetch data String value = jedis.get (keys); / / release object pool (3.0 will discard this method) sentinelpool.returnSentinelpoolResource (jedis)

Sample code

1. Simple append of String

/ / get a Jedis object JedisUtil.getInstance () .STRINGS.append (key, value) from the pool

two。 Price time order (provided that the SortSet of price and time has been stored)

/ / perform a 2-level sort operation ()

String stPriceSet = "stPriceSet"; / / sortset list name of stPriceSet price String stTimeSet = "stTimeSet"; / / sortset list name of stTimeSet time Set sumSet = JedisUtilEx.getInstance (). GetSortSetByPirceUpAndTimeDown (stPriceSet, stTimeSet); / / after sorting, you can get the last sort result (cache time 10 minutes) Set sumSet = JedisUtilEx.getInstance () getLastPirceUpAndTimeDownSet ()

3. Price time order (provided that the SortSet of price and time has been stored)

/ / perform a 2-level sort operation String stPriceSet = "stPriceSet"; / / sortset list name of stPriceSet price String stTimeSet = "stTimeSet"; / / sortset list name of stTimeSet time Set sumSet = JedisUtilEx.getInstance (). GetSortSetByPirceDownAndTimeDown (stPriceSet, stTimeSet); / / after sorting, you can get the last sort result (cache time is 10 minutes) Set sumSet = JedisUtilEx.getInstance () getLastPirceDownAndTimeDownSet ()

4. Save JavaBean to hash table

/ / bean inherits to RedisBeanJedisUtilEx.getInstance () .setBeanToHash (bean)

5. Read JavaBean from the hash table

/ / uuid's unique identifier rule for business (equivalent to primary key) String uuid = "1"; / / the ID is known in advance / / T inherits to RedisBean;JedisUtilEx.getInstance () .getBeanFromHash (uuid,Class cls)

6. Load the JavaBean list into hash

/ / bean in list inherits to RedisBeanList beanList =... ; JedisUtilEx.getInstance (). SetBeanListToHash (beanList); / / Asynchronous version of the storage list to hashJedisUtilEx.getInstance (). SetBeanListToHashSyn (beanList)

7. An example of a general operation flow

/ / get the jedis reference Jedis jedis = JedisUtil.getInstance (). GetJedis (); / / execute the business and call the interface functions provided by jedis. Jedis.hset (…) ;... / / be sure to release the resource JedisUtil.getInstance () .returnJedis (jedis) after the execution is completed; / / if you will not use JEDIS in the future, you need to close all link pools RedisConnetcion.destroyAllPools ()

8. Transaction execution process

/ / get the connection resource Jedis jd = JedisUtil.getInstance (). GetJedis (); / / Open the transaction Transaction ts = jd.multi (); / / execute the business and call the interface function provided by jedis. Jedis.hset (…) ;... / / execute transaction List list = ts.exec (); / / release resource JedisUtil.getInstance () .returnJedis (jd)

9. Asynchronous execution

/ / get the connection resource Jedis jedis = JedisUtil.getInstance (). GetJedis (); / get the pipeline Pipeline pipeline = jedis.pipelined (); / / execute the business and call the interface function provided by jedis. Jedis.hset (…) ;... / / commit and release pipeline pipeline.syncAndReturnAll (); / / release resource JedisUtil.getInstance () .returnJedis (jedis)

10. How to get the synthetic KEY of Jedis naming rules

/ / get the unique key value of the class key, for example: User:1 (User is class,1 and uuid), where user inherits from ReidsbeanJedisUtilEx.getInstance (). GetBeanKey (user); / / another method to obtain the class's unique key value key JedisUtilEx.getInstance (). GetBeanKey (String uuid,Class cls); / / get KEY corresponding to bean (key of the corresponding column) JedisUtilEx.getInstance (). GetBeanKey (String uuid,Class cls,String...) Fileds); / / get the KEY (cluster key) JedisUtilEx.getInstance () .getBeanKey (Class cls,String...) corresponding to bean Fileds)

4. Jedis operation command:

1. Commands for value operations

Exists (key): confirm whether a key exists del (key): delete a key type (key): return the type of value keys (pattern): return all key randomkey that satisfy a given pattern: a key rename (oldname, newname) that randomly returns the key space: rename key from oldname to newname Delete the key dbsize represented by newname if newname exists: return the number of key in the current database expire: set the active time of a key (s) ttl: get the active time of a key select (index): query move by index (key Dbindex): transfer the key in the current database to the database with dbindex index flushdb: delete all key flushall in the currently selected database: delete all key in all databases

two。 Commands for String operations

Set (key, value): assign the value value get (key) to the string named key in the database: return the value getset (key, value) of the string named key in the database: assign the last value mget (key1, key2,... , key N): returns multiple string in the library (their names are key1,key2... Value setnx (key, value): if there is no string named key, add string to the library with the name key and the value value setex (key, time, value): add string (name key, value value) to the library and set the expiration time time mset (key1, value1, key2, value2,... Key N, value N): assign multiple string values simultaneously. String named key I assigns value i msetnx (key1, value1, key2, value2, … Key N, value N): if all string named key I does not exist, add string to the library Name key I assigned to value i incr (key): string plus 1 operation incrby (key, integer): string increase integer decr (key) named key: string minus 1 operation decrby (key, integer): string minus integer append (key, value): string minus integer append (key, value): value of string named key appends value substr (key, start, end): returns a substring of value named key string

3. Commands for List operations

Rpush (key, value): add an element lpush (key, value) with the value value to the end of the list named key: add an element llen (key) with the value value to the list header named key: return the length of list named key lrange (key, start, end): return elements between start and end in list named key (subscript starting with 0, same below) ltrim (key, start, end): intercept list named key Keep the element lindex (key, index) between start and end: return the element lset (key, index, value) in the index position in the list named key: assign the element in the index position in the list named key to value lrem (key, count, value): delete count elements with the value value in list named key. If count is 0, delete all elements with the value of value, and delete all elements with the value of count from beginning to end, count0. If you encounter the above situation, wait for timeout seconds. If the problem is not solved, perform a pop operation on the list starting from key iTunes 1. Brpop (key1, key2, … Key N, timeout): the block version of rpop. Refer to the previous command. Rpoplpush (srckey, dstkey): returns and deletes the trailing element of the list named srckey and adds it to the header of the list named dstkey

4. Commands for Set operations

Sadd (key, member): add element member srem (key, member) to the set named key: delete the element member spop (key) in the set named key: randomly return and delete an element smove (srckey, dstkey, member) in the set named key: move the member element from the collection named srckey to the collection scard (key) named dstkey: return the cardinality sismember (key) of set named key Member): test whether member is the element sinter (key1, key2, …) of set named key. Key N): find the intersection sinterstore (dstkey, key1, key2, … Key N): find the intersection and save the intersection to the collection of dstkey sunion (key1, key2, … Key N): Union set sunionstore (dstkey, key1, key2, … Key N): join and save the union to the collection of dstkey sdiff (key1, key2,... Key N): sdiffstore (dstkey, key1, key2, … Key N): take the difference set and save the difference set to the collection of dstkey smembers (key): return all elements of set named key srandmember (key): randomly return one element of set named key

5. Commands for zset (sorted set) operations

Zadd (key, score, member): add the element member,score to the zset named key for sorting. If the element already exists, the order of the element is updated according to score. Zrem (key, member): delete the element member zincrby (key, increment, member) in the zset named key: if the element member already exists in the zset named key, the score of that element increases increment Otherwise, add the element to the collection with the value of score increment zrank (key, member): return the rank (that is, index, starting with 0) of the member element in the zset named key (the element has been sorted by score from smallest to largest). If there is no member element, return "nil" zrevrank (key, member): return the rank of the member element in zset with the name key (the element has been sorted by score from largest to smallest) (that is, index, starting with 0), if there is no member element Return "nil" zrange (key, start, end): return all elements index from start to end in zset named key (elements sorted by score from smallest to largest) zrevrange (key, start, end): return all elements zrangebyscore (key, min, max) of index from start to end in zset with name key (elements sorted by score from largest to smallest): return score > = min and score = min and rank = min and score in zset with name key

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.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report