Operating Redis in java code: single machine redis, cluster redis (spring+redis integration)

I. Preparation

  1. For some installations of redis, check out my articles to install them yourself: Redis directory.


  2. A web project, and one of the github projects I've been working on here is: https://github.com/gubaijin/buildmavenweb


  3. Edits client dependency package Jedis importing java:
    <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>2.9.0</version>
            </dependency>



2. Single-machine Redis

  1. Simple single machine code test:
    Jedis jedis = new Jedis("localhost");
    jedis.set("foo", "bar");
    String value = jedis.get("foo");

  2. Integrated with spring, you can click directly to view: J2ee project built from 0 (11): Integrate Redis in the project for data storage or caching


3. Connect redis cluster in code

//Connect the redis cluster in your code using jedis because it's a cluster and can be discovered automatically, as well as just one address
        Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();
        //Jedis Cluster will attempt to discover cluster nodes automatically
        jedisClusterNodes.add(new HostAndPort("192.168.240.142", 6379));
        JedisCluster jc = new JedisCluster(jedisClusterNodes);
        jc.set("foo", "bar");
        String value = jc.get("foo");
        System.out.println(value);
After running, it is found that it can be retrieved normally:

Using the redis client to view the validation in the redis cluster, we connected 142 When saving, and then we validated on 144:


4. spring-data-redis Connect to redis Cluster

Because it is not possible in practice to go newnewer and connect every time you use it, it is recommended that you use spring to integrate redis and use newer packages (lower versions may not support redis clusters).

  1. After importing the jedis package, you also import spring-data-redis:
    <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-redis</artifactId>
                <version>1.7.2.RELEASE</version>
            </dependency>





  2. Create a redisCluster.properties:
    #redis setting
    redis.host1=192.168.240.142
    redis.port1=6379
    
    #jedis setting
    jedis.maxIdle=6
    jedis.minEvictableIdleTimeMillis=300000
    jedis.numTestsPerEvictionRun=3
    jedis.timeBetweenEvictionRunsMillis=60000





  3. Create a spring-redisCluster.xml:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
           default-lazy-init="true">
    
        <context:component-scan base-package="com.spring.demo.redis" />
    
        <!-- Introduce redis configuration file -->
        <context:property-placeholder location="classpath:redisCluster.properties" />
    
        <!-- Connection pool configuration -->
        <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
            <!-- Maximum number of free connections in connection pool -->
            <property name="maxIdle" value="${jedis.maxIdle}"></property>
            <!-- The minimum time a connection is idle, after which the idle connection may be removed.negative(-1)Indicates no removal. -->
            <property name="minEvictableIdleTimeMillis" value="${jedis.minEvictableIdleTimeMillis}"></property>
            <!-- The number of link resources detected at a time for the idle link detection thread.Default 3 -->
            <property name="numTestsPerEvictionRun" value="${jedis.numTestsPerEvictionRun}"></property>
            <!-- "Idle Links"detects threads, detection cycles, milliseconds.A negative value means that Detect Threads is not running.Default to-1. -->
            <property name="timeBetweenEvictionRunsMillis" value="${jedis.timeBetweenEvictionRunsMillis}"></property>
        </bean>
    
        <!-- Cluster Configuration -->
        <bean id="jedisCluster" class="redis.clients.jedis.JedisCluster">
            <constructor-arg>
                <set>
                    <bean class="redis.clients.jedis.HostAndPort">
                    <constructor-arg name="host" value="${redis.host1}"/>
                    <constructor-arg name="port" value="${redis.port1}"/>
                </bean>
                </set>
            </constructor-arg>
            <constructor-arg name="poolConfig" ref="jedisPoolConfig"/>
        </bean>
    </beans>



  4. Create a new RedisClusterUtils.class to store some unified redis cluster operations:
    package com.spring.demo.redis;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import redis.clients.jedis.JedisCluster;
    
    import java.util.List;
    
    @Component
    public class RedisClusterUtils {
    
        @Autowired
        private JedisCluster jedisCluster;
    
        /**
         * Gets the value of the specified key value
         * @param key
         */
        public Object get(String key){
            return jedisCluster.get(key);
        }
    
        /**
         * Save the value of the specified key value
         * @param key
         * @param value
         */
        public void set(String key, String value){
            jedisCluster.set(key, value);
        }
    
        /**
         * Save the value of the specified key value
         * @param key
         * @param list
         */
        public void set(String key, List<String> list){
            jedisCluster.rpush(key, (String[]) list.toArray());
        }
    
        /**
         * Remove the value of the specified key
         * @param key
         */
        public void del(String key){
            jedisCluster.del(key);
        }
    }
    



  5. Code Run Validation:
            //spring Integrated redis Cluster
            ApplicationContext ctx = new ClassPathXmlApplicationContext("/spring-redisCluster.xml");
            RedisClusterUtils redisClusterUtils = (RedisClusterUtils) ctx.getBean("redisClusterUtils");
            redisClusterUtils.set("redisCluster", "RedisClusterUtils");
            System.out.println(redisClusterUtils.get("redisCluster"));





  6. Client command line connection cluster validation, this time we select 143 to validate

5. Data Address:

https://github.com/xetorthio/jedis








Published 85 original articles. Accepted 105. Access 950,000+
His message board follow

Tags: Redis Jedis Spring github

Posted on Tue, 24 Mar 2020 20:54:51 -0400 by eekeek