Home  >  Article  >  Java  >  Detailed explanation of examples of java operating redis cluster

Detailed explanation of examples of java operating redis cluster

零下一度
零下一度Original
2017-05-26 14:38:303474browse

Regarding Redis cluster construction, you can refer to my other article Redis cluster construction and simple use

What is Redis and what can it do

Redis is an open source (BSD licensed), in-memory data structure server that can be used as a database, cache, and message queue broker. It supports strings, hash tables, lists, sets, ordered sets, bitmaps, hyperloglogs and other data types. Built-in replication, Lua scripts, LRU eviction, transactions and different levels of disk persistence functions, while providing high availability through Redis Sentinel and automatic partitioning through Redis Cluster. (Excerpted from Redis official website)

As an in-memory database, Redis is still mainly used as a cache in modern Internet web systems. Large-scale Internet Web systems have high performance requirements, and adding data caching between the front end and the data layer has become one of the essential means. The two currently popular technologies are Redis and Memcached. As for the difference between the two, That’s not what this article is about. This article mainly talks about how Java web operates Redis and Redis cluster.

General Java program operation Redis

Redis provides clients in multiple languages, the most popular one in Java is Jedis. Visit to view the source code and how to use it. Currently the latest version of Jedis is 2.9.0. Whether it is a stand-alone machine or a cluster, Jedis has very detailed instructions and example codes. Here is only a brief explanation. If you use Maven for package management, you need to reference the jedis package. This example uses the latest 2.9.0 version, as follows:

  redis.clients      jedis      2.9.0  
操作 Redis 单机
import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig; /** * Created by fengdezitai on 2016/10/9. */public class JedisClient {     private static final String host= "192.168.31.121";     private static final JedisClient jedisClient = new JedisClient();     private Jedis jedis = null;    /**     * 私有构造函数     */    private JedisClient(){}     public static JedisClient getInstance(){        return jedisClient;    }     private JedisPoolConfig getPoolConfig(){        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();        jedisPoolConfig.setMaxIdle(10);        jedisPoolConfig.setMaxTotal(100);        jedisPoolConfig.setMaxWaitMillis(3000);        return jedisPoolConfig;    }     /**     * 添加     * @param key     * @param value     * @return     * @throws Exception     */    public Boolean add(String key,String value) throws Exception{        JedisPool pool = new JedisPool(getPoolConfig(),host);        Jedis jedis = null;        try {            jedis = pool.getResource();            if(jedis.exists(key)){                throw new Exception(String.format("key (%s) 已存在 ",key));            }            jedis.set(key,value);         }catch (Exception e){            throw e;        }        finally {            if(jedis!=null){                jedis.close();            }        }        pool.destroy();        return true;    }     /**     * 获取值     * @param key     * @return     * @throws Exception     */    public String get(String key) throws Exception{        JedisPool pool = new JedisPool(getPoolConfig(),host);        Jedis jedis = null;        String result = "";        try {            jedis = pool.getResource();            result = jedis.get(key);        }catch (Exception e){            throw e;        }        finally {            if(jedis!=null){                jedis.close();            }        }        pool.destroy();        return result;    }     public static void main(String[] args) {        JedisClient jedisClient = JedisClient.getInstance();        try {            /*Boolean result = jedisClient.add("hello", "redis1");            if(result){                System.out.println("success");            }*/             System.out.println(jedisClient.get("hello"));        }catch (Exception e){            e.printStackTrace();        }    }}

Operation redis cluster

import redis.clients.jedis.*;
import java.util.HashSet;
import java.util.Set;
 
/**
 * Created by fengdezitai on 2016/10/13.
 */
public class JedisClusterClient {
 
    private static int count = 0;
 
    private static final JedisClusterClient redisClusterClient = new JedisClusterClient();
 
    /**
     * 私有构造函数
     */
    private JedisClusterClient() {}
 
    public static JedisClusterClient getInstance() {
        return redisClusterClient;
    }
 
    private JedisPoolConfig getPoolConfig(){
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(1000);
        config.setMaxIdle(100);
        config.setTestOnBorrow(true);
        return config;
    }
 
    public void SaveRedisCluster() {
        Set jedisClusterNodes = new HashSet();
        jedisClusterNodes.add(new HostAndPort("192.168.31.245", 7000));
        jedisClusterNodes.add(new HostAndPort("192.168.31.245", 7001));
        jedisClusterNodes.add(new HostAndPort("192.168.31.245", 7002));
        jedisClusterNodes.add(new HostAndPort("192.168.31.210", 7003));
        jedisClusterNodes.add(new HostAndPort("192.168.31.210", 7004));
        jedisClusterNodes.add(new HostAndPort("192.168.31.210", 7005));
 
        JedisCluster jc = new JedisCluster(jedisClusterNodes,getPoolConfig());
        jc.set("cluster", "this is a redis cluster");
        String result = jc.get("cluster");
        System.out.println(result);
    }
 
    public static void main(String[] args) {
        JedisClusterClient jedisClusterClient = JedisClusterClient.getInstance();
        jedisClusterClient.SaveRedisCluster();
    }
}  

Spring mvc operation Redis

To operate Redis in Spring mvc, of course you must first set up the Spring mvc framework. The following is assuming that the Spring mvc environment has been set up. In this example, the Spring version is 4.3.2 RELEASE. The maven reference about Spring is as follows:

4.3.2.RELEASE 
    
          org.springframework      spring-core      ${spring.version}                        commons-logging          commons-logging                   
          org.springframework      spring-web      ${spring.version}     
          org.springframework      spring-oxm      ${spring.version}     
          org.springframework      spring-tx      ${spring.version}     
          org.springframework      spring-jdbc      ${spring.version}     
          org.springframework      spring-webmvc      ${spring.version}                        commons-logging          commons-logging                   
          org.springframework      spring-aop      ${spring.version}     
          org.springframework      spring-context-support      ${spring.version}     
 
          org.springframework      spring-test      ${spring.version}

Operation Redis stand-alone

Only use Jedis to implement the injection (different from the following reference spring-data-redis)

Replace the previous The JedisClient code can be referenced. You only need to implement a Service to access Redis, and it can be integrated into Spring mvc. The Service code is as follows:

import org.springframework.stereotype.Service;
import util.JedisClient;
 
/**
 * Created by fengdezitai on 2016/10/9.
 */
@Service
public class RedisService {
 
    public String get(String key) throws Exception{
        JedisClient jedisClient = JedisClient.getInstance(); //上面实现的JedisClient
        String result = "";
        try {
            result = jedisClient.get("hello");
        }catch (Exception e){
            throw e;
        }
        return result;
    }
}

Controller is implemented as follows:

@Controller
@RequestMapping(value = "redisAllInOne")
public class RedisAllInOneController {
 
    @Autowired
    private RedisService redisService;
 
    @RequestMapping(value = "get",method = RequestMethod.GET)
    @ResponseBody
    public Object getByMyService(String key){
        try {
            String result = redisService.get(key);
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}  

Use spring-data-redis package for integration

The above is the injection implemented by myself, here spring-data- To integrate redis, you only need simple configuration. You need to reference the maven package as follows. The version is the latest version 1.7.2.RELEASE:

      org.springframework.data      spring-data-redis      1.7.2.RELEASE

Use spring-data-redis, which eliminates the need to implement the injection yourself. process, through some configurations it provides, you can realize connection pool configuration, RedisTemplate configuration, JedisConnectionFactory configuration; through JedisConnectionFactory, you can configure the connection pool parameters, redis server, port, password, timeout, database index, etc.; RedisTemplate is the injected bean, You can use the entities automatically injected by RedisTemplate to perform a series of operations on redis, depending on the configuration;

redis service attribute configuration file:

redis.maxIdle=300redis.maxWait=3000redis.testOnBorrow=trueredis.host=192.168.31.121redis.port=6379redis.password=passwordredis.timeout=3000
spring-data-redis xml 配置文件 redis-context.xml:                                                              -->                                                                                                          -->

After that, reference the above file in the spring configuration file:

Explain the above configuration:

poolConfig configures the redis connection pool, and then configures two JedisConnectionFactory and RedisTemplate. One RedisTemplate corresponds to one JedisConnectionFactory, so that different Redis connections can be configured according to the scenario. , such as inconsistent timeout requirements, database 0-15 can store different data, etc. Database 1 and 2 are configured here. Calling commonRedisTemplate will save it to database1, and calling cacheRedisTemplate will save it to database2.

Afterwards, these two RedisTemplates can be injected and referenced in the Service layer, as shown below:

import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
 
import javax.annotation.Resource;
import java.io.*;
 
@Repository
public class RedisCache {  
    @Resource(name = "cacheRedisTemplate")
    private RedisTemplate

Finally, call them in the Controller

@Autowired
private RedisCache redisCache;
 
 
@RequestMapping(value = "get", method = RequestMethod.GET)
@ResponseBody
public Object getByMyService(String key) {
    try {
        String result = redisService.get(key);
        return result;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
@RequestMapping(value = "save", method = RequestMethod.GET)
@ResponseBody
public Object save() {
    Token token = new Token();
    token.setAccess_token("token");
    token.setExpires_in(1000);
    try {
        redisCache.put("token", token);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "ok";
}  

to operate the Redis cluster

Only use Jedis to implement the injection (different from the reference below spring-data-redis)

Just take the previous JedisClusterClient code and reference it. You only need to implement a Service to access Redis. It can be integrated into Spring mvc. The Service code is as follows:

import org.springframework.stereotype.Service;
import util.JedisClusterClient;
 
/**
 * Created by fengdezitai on 2016/10/13.
 */
@Service
public class RedisClusterService {
 
    public void save() throws Exception{
        //调用 JedisClusterClient 中的方法
        JedisClusterClient jedisClusterClient = JedisClusterClient.getInstance();
        try {
            jedisClusterClient.SaveRedisCluster();
        }catch (Exception e){
            throw e;
        }
    }
}

Finally call the implemented Service in the Controller

@Controller
@RequestMapping(value = "redisCluster")
public class RedisClusterController {
 
    @Autowired
    private RedisClusterService redisClusterService;
 
    @RequestMapping(value = "save",method = RequestMethod.GET)
    @ResponseBody
    public Object save(){
        try{
            redisClusterService.save();
        }catch (Exception e){
            e.printStackTrace();
            return String.format("error: %s",e.getMessage());
        }
        return "ok";
    }
}  

Note:

Version issue, if you use spring-data-redis for integration operations Reids cluster, only the latest version 1.7 of spring-data-redis includes cluster operations, and some functions in the latest spring-data-redis also have some restrictions on the version of Spring mvc, so try to choose a higher version of Spring mvc correspond.

If the stored value is an entity object, then the Serializable interface must be implemented

[Related recommendations]

1. Detailed explanation of the usage code of Spring framework annotations Example

2. Java transaction management learning: Detailed code explanation of Spring and Hibernate

3. Sharing an example tutorial on using Spring Boot to develop Restful programs

4. Detailed explanation of the seven return methods supported by spring mvc

5. Detailed explanation of Spring’s enhanced implementation examples based on Aspect

6. Example of PHPRPC for Java Spring

8. Detailed explanation of practical tutorials on using Elasticsearch in spring

The above is the detailed content of Detailed explanation of examples of java operating redis cluster. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn