In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article focuses on "how to connect with Redis Java". 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 method of Redis Java connection.
1. Java connection pool connection (pipe, lua)
Add the following dependencies
Redis.clientsjedis2.9.01, Testpublic class Test {public static void main (String [] args) {JedisPoolConfig jedisPoolConfig = new JedisPoolConfig (); jedisPoolConfig.setMaxTotal (20); jedisPoolConfig.setMaxIdle (10); jedisPoolConfig.setMinIdle (5); / / timeout, where there is both connection timeout and read and write timeout. Since Jedis 2.8there is a constructor JedisPool jedisPool = new JedisPool (jedisPoolConfig, "192.168.157.6", 6379, 3000, null) that distinguishes connectionTimeout from soTimeout; Jedis jedis = null Try {/ / take a connection from the redis connection pool to execute the command jedis = jedisPool.getResource (); System.out.println (jedis.set ("single", "zhuge")); System.out.println (jedis.get ("single")); / / pipeline example / / command execution mode of the pipe: cat redis.txt | redis-cli-h 127.0.0.1-a password-p 6379-- pipePipeline pl = jedis.pipelined (); for (int I = 0; I
< 10; i++) {pl.incr("pipelineKey");pl.set("zhuge" + i, "zhuge");}List results = pl.syncAndReturnAll();System.out.println(results);// lua脚本模拟一个商品减库存的原子操作// lua脚本命令执行方式:redis‐cli ‐‐eval /tmp/test.lua , 10jedis.set("product_count_10016", "15"); // 初始化商品10016的库存String script = " local count = redis.call('get', KEYS[1]) " +" local a = tonumber(count) "+" local b = tonumber(ARGV[1]) " +" if a >= b then "+" redis.call ('set', KEYS [1], count-b) "+" return 1 "+" end "+" return 0 "; System.out.println (" script: "+ script); Object obj = jedis.eval (script, Arrays.asList (" product_count_10016 "), Arrays.asList (" 10 ")); System.out.println (obj);} catch (Exception e) {e.printStackTrace () } finally {/ / Note that the connection is not closed here. In JedisPool mode, Jedis is returned to the resource pool. If (jedis! = null) jedis.close ();}} 2, pipe (Pipeline)
The client can send multiple requests at one time without waiting for the response of the server, and then read the response of the service at one time after all the commands have been sent, which can greatly reduce the network transmission overhead of multiple command executions. in fact, the network overhead of pipeline executing multiple commands is only equivalent to the network overhead of one command execution. Note that commands are packaged and sent in pipeline mode, and redis must cache the processing results of all commands before processing them. The more commands are packaged, the more memory is consumed by the cache. So it's not that the more commands you pack, the better. Every command sent in the pipeline is executed immediately by the server, and if the execution fails, you will get the information in the subsequent response; that is, pipeline does not express the semantics of "all command succeed together." the previous command in the pipeline fails, and the subsequent command will not be affected.
The example is referred to above.
3. Redis Lua script
Redis introduced scripting functionality in 2.6.It allows developers to write scripts in Lua language and transfer them to Redis for execution. The benefits of using scripts are as follows:
1. Reduce network overhead
The operation of the original five network requests can be completed with one request, and the logic of the previous five requests can be completed on the redis server. The use of scripts reduces the network round-trip delay. This is similar to plumbing.
2. Atomic operation
Redis executes the entire script as a whole without being inserted by other commands. Pipes are not atomic, but redis's bulk operation commands (similar to mset) are atomic.
3. Replace the transaction function of redis
The transaction feature of redis is very scary, and rollback is not supported when errors are reported. However, redis's lua script almost shows the regular transaction function and supports error rollback operation. It is officially recommended that redis lua can be used instead of redis's transaction function.
There is a passage on the official website:
A Redis script is transactional by definition, so everything you can do with a Redis transaction, you can also do with a script,and usually the script will be both simpler and faster.
Starting with the Redis2.6.0 version, Lua scripts can be evaluated using the EVAL command through the built-in Lua interpreter. Lattice of the EVAL command
The formula is as follows:
EVAL script numkeys key [key...] Arg [arg...]
The script parameter is a Lua script that will be run in the context of the Redis server, and this script does not have to (and should not) be defined as a
A Lua function. The numkeys parameter is used to specify the number of key name parameters. Key name parameter key [key...] Calculate from the third parameter of EVAL
Represents the key keys used in the script, and these key name parameters can be passed through the global variable KEYS array in Lua, using 1
Access as a base address (KEYS [1], KEYS [2], and so on). At the end of the command, those additional parameters that are not key name parameters arg [arg...] Can be accessed in Lua through an array of global variables ARGV in a form similar to KEYS variables (ARGV [1], ARGV [2], and so on). For example
127.0.1 KEYS 6379 > eval "return {KEYS [1], KEYS [2], ARGV [1], ARGV [2]}" 2 key1 key2 first second2 1) "key1" 3 2) "key2" 4 3) "first" 5 4) "second"
Where "return {KEYS [1], KEYS [2], ARGV [1], ARGV [2]}" is the Lua script being evaluated, and the number 2 specifies the number of key name parameters.
Quantity, key1 and key2 are key name parameters, accessed using KEYS [1] and KEYS [2], respectively, while the final first and second are appended
Parameters, which can be accessed through ARGV [1] and ARGV [2]. In the Lua script, you can use the redis.call () function to execute the Redis command
The example is referred to above.
Note that there are no endless loops and time-consuming operations in the Lua script, otherwise redis will block and will not accept other commands, so use the
Be careful not to have endless loops and time-consuming operations. Redis is a single-process, single-threaded execution script. The pipe does not block the redis.
2. Jedis connection code public class Test2 {public static void main (String [] args) {JedisPoolConfig jedisPoolConfig = new JedisPoolConfig (); jedisPoolConfig.setMaxTotal (20); jedisPoolConfig.setMaxIdle (10); jedisPoolConfig.setMinIdle (5); String masterName = "mymaster"; Set sentinels = new HashSet (); sentinels.add (new HostAndPort ("192.168.157.6", 26379). ToString ()); sentinels.add ("192.168.157.6", 26380). ToString ()) Sentinels.add (new HostAndPort ("192.168.157.6", 26381). ToString ()); / / timeout, where there is both connection timeout and read and write timeout. Since Jedis 2.8there is a constructor JedisSentinelPool jedisSentinelPool = new JedisSentinelPool (masterName, sentinels, jedisPoolConfig, 3000, null) that distinguishes connectionTimeout from soTimeout; Jedis jedis = null;try {/ / take a connection execution command jedis = jedisSentinelPool.getResource () from the redis connection pool; while (true) {Thread.sleep (1000) Try {System.out.println (jedis.set ("single", "zhuge")); System.out.println (jedis.get ("single"));} catch (Exception e) {/ / TODO Auto-generated catch blocke.printStackTrace ();} catch (Exception e) {e.printStackTrace ();} finally {/ / Note that the connection is not closed here, and Jedis is returned to the resource pool in JedisPool mode. If (jedis! = null) jedis.close () 3. Spring Boot integration Redis connection of Sentinel 1, introduction of related dependencies org.springframework.bootspring-boot-starter-data-redisorg.apache.commonscommons-pool22, core configuration of springboot project server:port: 8080spring:redis:database: 0timeout: 3000sentinel: # Sentinel mode master: mymaster # Cluster name of master server nodes: 192.168.0.60:26379192.168.0.60:26380192.168.0.60:26381lettuce:pool:max-idle: 50min-idle: 10max-active: 100max-wait: 10003, Access code @ RestControllerpublic class IndexController {private static final Logger logger = LoggerFactory.getLogger (IndexController.class) @ Autowiredprivate StringRedisTemplate stringRedisTemplate / * the test node hung up the sentinel to re-elect a new master node, and whether the client can dynamically perceive it. * after the new master is elected, the Sentinel will publish the message. The client actually implements a message monitoring mechanism. * when the Sentinel publishes the message of the new master, the client will immediately perceive the information of the new master. Thus dynamically switch the accessed masterip* @ throws InterruptedException*/@RequestMapping ("/ test_sentinel") public void testSentinel () throws InterruptedException {int I = 1 While (true) {try {stringRedisTemplate.opsForValue (). Set ("zhuge" + I, I + "); System.out.println (" set key: "+" zhuge "+ I); catch (Exception e) {logger.error (" error: ", e);} 4, StringRedisTemplate and RedisTemplate
Spring encapsulates RedisTemplate objects to perform various operations on redis, and it supports all redis native api. In
Several common interface methods are provided in RedisTemplate, which are:
Private ValueOperations valueOps;private HashOperations hashOps;private ListOperations listOps;private SetOperations setOps;private ZSetOperations zSetOps
Operations on five data structures are defined in RedisTemplate
RedisTemplate.opsForValue (); / / Operation string redisTemplate.opsForHash (); / / Operation hashredisTemplate.opsForList (); / / Operation listredisTemplate.opsForSet (); / / Operation setredisTemplate.opsForZSet (); / / Operation orderly set
StringRedisTemplate inherits from RedisTemplate and also owns the above operations.
By default, StringRedisTemplate adopts the serialization strategy of String, and both key and value are serialized and saved by this policy.
Of. RedisTemplate defaults to the serialization strategy of JDK, and the saved key and value are serialized and saved using this policy.
That is, if you use RedisTemplate to save the content, you will see in the console will be a lot of encoded characters, more difficult to understand.
List of methods in the RedisTemplate corresponding to Redis client commands:
4. Jedis connection code public class Test3 {public static void main (String [] args) throws IOException {JedisPoolConfig jedisPoolConfig = new JedisPoolConfig (); jedisPoolConfig.setMaxTotal (20); jedisPoolConfig.setMaxIdle (10); jedisPoolConfig.setMinIdle (5); Set jedisClusterNode = new HashSet (); jedisClusterNode.add (new HostAndPort ("192.168.0.61", 8001)); jedisClusterNode.add (new HostAndPort ("192.168.0.62", 8002)); jedisClusterNode.add ("192.168.0.63", 8003)) JedisClusterNode.add (new HostAndPort ("192.168.0.61", 8004); jedisClusterNode.add (new HostAndPort ("192.168.0.62", 8005)); jedisClusterNode.add (new HostAndPort ("192.168.0.63", 8006)); / / timeout, where there is both connection timeout and read and write timeout. Since Jedis 2.8, there is a constructor JedisCluster jedisCluster = new JedisCluster (jedisClusterNode, 6000, 5000, 10, "zhuge", jedisPoolConfig) that distinguishes connectionTimeout from soTimeout. Try {while (true) {Thread.sleep (1000); try {System.out.println (jedisCluster.set ("single", "zhuge")); System.out.println (jedisCluster.get ("single"));} catch (Exception e) {/ / TODO Auto-generated catch blocke.printStackTrace ();}} catch (Exception e) {e.printStackTrace ();} finally {/ / Note that instead of closing the connection, Jedis is returned to the resource pool in JedisPool mode. If (jedisCluster! = null) jedisCluster.close ();} V. Cluster mode Springboot integrates redis
In fact, the cluster mode is very similar to the Sentinel mode, except that the configuration file can be modified.
Maximum idle connection in server:port: 8080spring:redis:database: 0timeout: 3000password: zhugecluster:nodes:192.168.0.61:8001192.168.0.62:8002192.168.0.63:8003lettuce:pool:# connection pool max-idle: 5 "minimum idle connection in connection pool min-idle: 10max-active: 10 connection pool blocking wait time (negative value indicates no limit) max-wait: 1000
It's just that sentinel is replaced by cluster, and then API and everything is the same.
At this point, I believe that you have a deeper understanding of the "method of Redis Java connection", you might as well come to the actual operation! 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.