Home Web Front-end JS Tutorial Java Spring mvc operates Redis and Redis cluster

Java Spring mvc operates Redis and Redis cluster

May 26, 2017 pm 02:40 PM

About 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 license), memory-stored 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, in modern Internet web systems, Redis is still mainly used as a cache. 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 most popular technologies currently 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 programs operate 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  
Copy after login

Operation Redis stand-alone

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();
        }
    }
}
Copy after login

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();
    }
}  
Copy after login

Spring mvc operation Redis

Operation in Spring mvc Redis, of course, we 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}
Copy after login

Operate Redis stand-alone

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

Just take the previous JedisClient code and quote it, you only need to implement one Accessing the Redis Service 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;
    }
}
Copy after login

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;
    }
}  
Copy after login

Use the spring-data-redis package for integration

The above is the injection implemented by myself. Here, spring-data-redis is used for integration. It only requires simple configuration. You need The reference to the maven package is as follows, the version is the latest version 1.7.2.RELEASE:

      org.springframework.data      spring-data-redis      1.7.2.RELEASE
Copy after login

Using spring-data-redis eliminates the need to implement the injection process by yourself. Through some of the configurations it provides, you can achieve 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, and you can use the entities automatically injected by RedisTemplate to perform a series of redis operations. For details, see Configuration;

redis service attribute configuration file:

redis.maxIdle=300
redis.maxWait=3000
redis.testOnBorrow=true
redis.host=192.168.31.121
redis.port=6379
redis.password=password
redis.timeout=3000
Copy after login

spring-data-redis xml configuration file redis-context.xml:

                                    
                                    -->
                     
                                                 
                                    -->
Copy after login

Then quote the above file in the spring configuration file:

  
Copy after login

Explain the above configuration:

poolConfig configures the redis connection pool, and then configures two JedisConnectionFactory and RedisTemplate. One RedisTemplate corresponds to one JedisConnectionFactory. In this way, 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, you can inject and reference these two RedisTemplates in the Service layer, as follows:

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
Copy after login

Finally call it 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";
}  
Copy after login

To operate the Redis cluster

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

Just take the previous JedisClusterClient code and reference it. 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.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;
        }
    }
}
Copy after login

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";
    }
}  
Copy after login

Use the spring-data-redis package for integration

The Spring and spring-data-redis maven package references are the same as before. The reason why spring- data-redis 1.7.2.RELEASE, because currently only this latest version supports cluster operations.

redis cluster service attribute configuration

redis.maxIdle=300
redis.maxWait=3000
redis.testOnBorrow=false
redis.timeout=3000
Copy after login

spring-data-redis xml cluster configuration file redis-cluster-context.xml

<br/>
Copy after login
Copy after login

will be later referenced in the Spring configuration file

<br/>
Copy after login
Copy after login

Explain the above configuration:

poolConfig is the connection pool configuration , redisClusterConfig configures each node of the Redis cluster (node ​​host and port are best written in the attribute configuration file). The cluster construction can be found in my other blog. Then the following is the same as the stand-alone configuration, a pair of JedisConnectionFactory and RedisTemplate.

Afterwards, this RedisTemplate can be injected and referenced in the Service layer. The code is as follows:

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 java.io.*;
 
/**
 * Created by fengdezitai on 2016/9/29.
 */
@Repository
public class RedisClusterCache {
 
    @Autowired
    private RedisTemplate clusterRedisTemplate;
 
 
    public void put(Object key, Object value) {
        if(null == value) {
            return;
        }
 
        if(value instanceof String) {
            if(StringUtils.isEmpty(value.toString())) {
                return;
            }
        }
 
        // TODO Auto-generated method stub
        final String keyf = key + "";
        final Object valuef = value;
        final long liveTime = 86400;
 
        clusterRedisTemplate.execute(new RedisCallback
Copy after login

Finally, just call it in the Controller

@Controller
@RequestMapping(value = "redisCluster")
public class RedisClusterController {
 
    @Autowired
    private RedisClusterCache redisClusterCache;
 
    @RequestMapping(value = "clusterSave",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Object clusterSave(){
        //redisClusterCache.put("cluster","save cluster");
        Token token = new Token();
        token.setExpires_in(1000);
        token.setAccess_token("hello world");
        redisClusterCache.put("token",token);
        return "ok";
    }
 
    @RequestMapping(value = "getKey",method = RequestMethod.GET)
    @ResponseBody
    public Object getCluster(String key){
        Object val = redisClusterCache.get(key);
        return val;
    }
} 
Copy after login

Notes:

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

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

[Related recommendations]

1. Detailed explanation of usage code examples of Spring framework annotations

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

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles