Basic Usage of Redis in Java

Time:2023-10-13

This movie introduces you to the basic use of Redis in Java.



1, using jedis operation redis

1.1 Introduction to Jedis

Jedis is a Redis client toolkit developed in the Java language for interacting with Redis data.

Jedis on github official site address:https://github.com/redis/jedis#readme

Jedis is just an encapsulation of Redis commands. You can easily get started with Jedis by mastering Redis commands.

Jedis has been developed according to the RESP protocol specification, which provides good generalization and readability.

1.2 Introducing Maven dependencies for jedis
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>4.4.3</version>
        </dependency>
1.2. Getting Connected

For many applications, it is necessary to connect to Redis. It is best to use connection pools. A Jedis connection pool can be instantiated like this.

JedisPool pool = new JedisPool("localhost", 6379);

For JedisPool instances, you can use the try-With-resources block to get a connection and run Redis commands (this way you don’t have to manually close it yourself).

try (Jedis jedis = pool.getResource()) {
	// Run a single SET command
  jedis.set("clientName", "Jedis");
}
1.3 Examples of use

Write the following code:

public static void main(String[] args) {
        // Redis server IP and port number
        JedisPool pool = new JedisPool("127.0.0.1", 6379);
        try (Jedis jedis = pool.getResource()) {
            // Use the relevant Redis commands
            // Select database 0 for operation
            jedis.select(0);
            // Write to database 0, string data.
            jedis.set("Java", "best");
            jedis.set("PHP", "good");
            // Query whether to write
            System.out.println(jedis.get("Java"));
            System.out.println(jedis.get("PHP"));
        }
    }

Running Test Cases.

Basic Usage of Redis in Java

A Jedis instance implements most of the Redis commands that can be found in thehttps://www.javadoc.io/doc/redis.clients/jedis/latest/redis/clients/jedis/Jedis.htmlApI The method corresponding to the query command in

Basic Usage of Redis in Java


2, for the use of JedisPooled

2.1 Using JedisPooled

Using try-with-resources blocks for each command can be cumbersome, so we can consider using JedisPooled.

JedisPooled jedis = new JedisPooled("localhost", 6379);

Detailed Code.

public static void main(String[] args) {
        JedisPooled pool = new JedisPooled("127.0.0.1", 6379, null, null);
        pool.set("Java", "best");
        pool.set("PHP", "good");
        System.out.println(pool.get("Java"));
        System.out.println(pool.get("PHP"));
    }

Runtime effect:

Basic Usage of Redis in Java

2.2 About connection pooling

The use of link pooling is the official recommended way to use , through the connection pool can be a better use of Jedis , we can through the GenericObjectPoolConfig connection pool related configuration , GenericObjectPoolConfig API documentation:https://commons.apache.org/proper/commons-pool/apidocs/org/apache/commons/pool2/impl/GenericObjectPoolConfig.html

Configure the connection pool with the GenericObjectPoolConfig object as follows.

public static void main(String[] args) {
        GenericObjectPoolConfig config = new JedisPoolConfig();
        // Set the connection pool to allow up to 100 Jedis objects.
        config.setMaxTotal(100);
        // Set the maximum number of free connections allowed in the connection pool.
        config.setMaxIdle(100);
        // Set the minimum number of connections allowed in the connection pool
        config.setMinIdle(10);
        // Whether to test for validity when lending connections, recommend false.
        config.setTestOnBorrow(false);
        // Test on return, false recommended.
        config.setTestOnReturn(false);
        // Test for validity at creation time Set to false for development, true for practice.
        config.setTestOnCreate(false);
        // If or not to wait for resources when jedis has no resources available in the connection pool, true.
        config.setBlockWhenExhausted(true);
        // Wait up to 1 second for a resource that is not available, and report an error if it's not available after 1 second.
        config.setMaxWaitMillis(1000);

        JedisPool pool = new JedisPool(config, "127.0.0.1", 6379);

        try (Jedis jedis = pool.getResource()) {
            // Use the relevant Redis commands
            // Select database 0 for operation
            jedis.select(0);
            // Write to database 0, string data.
            jedis.set("Java", "best");
            jedis.set("PHP", "good");

            // Query whether to write
            System.out.println(jedis.get("Java"));
            System.out.println(jedis.get("PHP"));
        }
    }

Runtime effect:

Basic Usage of Redis in Java


3, SpringBoot under the use of Redis

3.1 Introducing Maven dependencies

First, you need to add a Redis dependency in the pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

This dependency contains implementations of Spring Data Redis, as well as two Redis clients, Jedis and Lettuce.

3.2 Configuring Redis Connections

In a SpringBoot project, you can configure Redis connection information by configuring it in the application.properties or application.yml file. The following is an example:

spring:
  data:
    redis:
      timeout: 3000
      database: 0
      password: password
      port: 6379
      host: localhost

Among them, host and port are the address and port number of the Redis server, respectively, password is the Redis password (if you don’t have a password, you can leave it out), timeout is the Redis connection timeout time, and jedis.pool is the relevant settings for the connection pool.

3.3 Creating a RedisTemplate

To manipulate Redis with Spring Data Redis, you typically use the RedisTemplate class. For convenience, we can create a tool class to manage the creation and use of RedisTemplate. Here is an example:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtils {

    /**
     * If autowiring is done using the @Autowired annotation then the
     * RedisTemplate either doesn't specify a generic, or the generic is <Stirng,String> or <Object,Object>.
     * If you use another type, such as RedisTemplate<String,Object>.
     * then use the @Resource annotation
     * */
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * Cache value
     *
     * @param key -
     * @param value -
     * @param time -
     * @return -
     */
    public boolean cacheValue(String key, Object value, long time) {
        try {
            ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
            valueOperations.set(key, value);
            if (time > 0) {
                // If a timeout is set
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Throwable e) {
            Logger. The error (" cache "+ key +" failures, the value/value + "" +" + um participant etMessage ());
        }
        return false;
    }

    /**
     * Cache value,没有设置超时时间
     *
     * @param key -
     * @param value -
     * @return -
     */
    public boolean cacheValue(String key, Object value) {
        return cacheValue(key, value, -1);
    }

    /**
     * :: Determining whether a cache exists
     *
     * @param key
     * @return
     */
    public boolean containsKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Throwable e) {
            logger.error("Failed to determine if cache exists key[" + key + "]", "err[" + e.getMessage() + "]");
        }
        return false;
    }

    /**
     * :: Fetch cache based on key
     *
     * @param key -
     * @return -
     */
    public Object getValue(String key) {
        try {
            ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
            return valueOperations.get(key);
        } catch (Throwable e) {
            logger.error("Failed to fetch cache key[" + key + "]", "err[" + e.getMessage() + "]");
        }
        return null;
    }

    /**
     * :: Removal of caches
     *
     * @param key -
     * @return -
     */
    public boolean removeValue(String key) {
        try {
            redisTemplate.delete(key);
            return true;
        } catch (Throwable e) {
            logger.error("Failed to remove cache on key[" + key + "]", "err[" + e.getMessage() + "]");
        }
        return false;
    }

    /**
     * :: Remove all key-values that begin with an incoming prefix based on the prefix
     *
     * @param pattern -
     * @return -
     */
    public boolean removeKeys(String pattern) {
        try {
            Set<String> keySet = redisTemplate.keys(pattern + "*");
            redisTemplate.delete(keySet);
            return true;
        } catch (Throwable e) {
            logger.error("Failed to remove key[" + pattern + "] prefixed cache", "err[" + e.getMessage() + "]");
        }
        return false;
    }

}

In this example, we use the@Resource annotation automatically injects aRedisTemplate<String, Object> object. We then provide three methods to manipulate Redis: the cacheValue method to cache data, the getValue method to retrieve cached data, and the removeValue method to remove cached data. These methods are implemented using the redisTemplate object.

Note that when using RedisTemplate, you need to specify the type of the key-value pair. In this example, we have specified the type of the key as String and the type of the value as Object.

3.4 Using RedisTemplate

In the above example, we have created a RedisTemplate object and provided some methods to perform operations on Redis. Now, we can use this tool class anywhere in our SpringBoot project to perform caching operations. Here is an example:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UserService userService;

    @GetMapping("/users/{id}")
    public User getUserById(@PathVariable Long id) {

        String key = "user_" + id;
        User user = (User) redisUtils.getValue(key);
        if (user == null) {
            user = userService.getUserById(id);
            redisUtils.cacheValue(key, user);
        }
        return user;
    }
}

In this example, we have created a UserController class to handle HTTP requests. In the getUserById method, we first construct a cached key and then use theredisUtils.getValue method to get the cached data from Redis. If there is no data in the cache, we call theuserService.getUserById method to get the data from the database and use theredisUtils.cacheValue method stores the data into the Redis cache. Finally, return the fetched data.

With this example, we can see the flow of using Redis as a cache in a S pringBoot project. We first need to add a Redis dependency and then configure the Redis connection information in a configuration file. Next, we create a RedisUtil s tool class to manage the creation and use of the RedisTemplate. Finally, we use RedisUtils in the controller to perform caching operations on Redis.

Recommended Today

uniapp and applet set tabBar and show and hide tabBar

(1) Set the tabBar: uni.setTabberItem({}); wx.setTabberItem({}); indexnumberisWhich item of the tabBar, counting from the left, is indexed from 0.textstringnoButton text on tabiconPathstringnoImage PathselectedIconPathstringnoImage path when selectedpagePathstringnoPage absolute pathvisiblebooleannotab Whether to display uni.setTabBarItem({ index: 0, text: ‘text’, iconPath: ‘/path/to/iconPath’, selectedIconPath: ‘/path/to/selectedIconPath’, pagePath: ‘pages/home/home’ }) wx.setTabBarItem({ index: 0, text: ‘text’, iconPath: ‘/path/to/iconPath’, selectedIconPath: ‘/path/to/selectedIconPath’, pagePath: ‘pages/home/home’ }) […]