Redis application - using Redis in Java and the Spring

A, Java use Redis

1. Import dependent Redis

Add Jedis (Java Redis) in pom file depend on: (specific version based on the actual use case may be)

<dependency>
     <groupId>redis.clients</groupId>
     <artifactId>jedis</artifactId>
     <version>2.6.0</version>
 </dependency>

You can also manually download the jar package into the project: https://mvnrepository.com/artifact/redis.clients
Here Insert Picture Description

2, write a test class Redis

@Test
public void redisTester() {
    Jedis jedis = new Jedis("localhost", 6379, 100000);
    int i = 0;
    try {
        long start = System.currentTimeMillis();// 开始毫秒数
        while (true) {
            long end = System.currentTimeMillis();
            if (end - start >= 1000) {// 当大于等于1000毫秒(相当于1秒)时,结束操作
                break;
            }
            i++;
            jedis.set("test" + i, i + "");
        }
    } finally {// 关闭连接
        jedis.close();
    }
    // 打印1秒内对Redis的操作次数
    System.out.println("redis每秒操作:" + i + "次");
}
-----------测试结果-----------
redis每秒操作:10365

At the same time, Jedis also provides classes redis.clients.jedis.JedisPool used to create connection pool Redis objects.
With this object class requires the connection pool configuration redis.clients.jedis.JedisPoolConfig

//先创建Redis配置对象
JedisPoolConfig poolCfg = new JedisPoolConfig();
//最大空闲数
poolCfg.setMaxIdle(50);
//最大连接数
poolCfg.setMaxTotal(100);
//最大等待毫秒数
poolCfg.setMaxWaitMillis(20000);
//使用配置对象创建连接池对象
JedisPool pool = new JedisPool (poolCfg, "localhost");
//从连接池中获取单个连接
Jedis jedis = pool.getResource();
//如果需密码
//jedis.auth("password");

Since Redis can only provide a string-based operation, while it used to in Java class object based, it is necessary to store Redis string conversion and Java objects.

If you write your own rules, the workload is quite large, such as a role object, we have no way to directly target into Redis, the need for further conversion, so the target for the operation, use Redis is quite difficult.

Fortunately, these Spring is encapsulated and support, which provides a sequence of some of the sequences of the design framework classes and after use it can be serialized by converting the Java object, so that it can Redis stored.

And at the time of reading, and then transformed by the sequence of Java objects through the string, so that use in a Java environment Redis more simple, so more time may RedisTemplate Spring provides mechanisms using Redis use .

Two, Spring use Redis

Use in Spring Redis, in addition to jedis.jar, but also need to download the Spring-the Data-redis.jar , worth noting here that the jar package and the Spring version compatibility problems , use the jar package version is 1.8.1 test, and Spring version is 5.0.4, there may be compatibility problems if you use other versions, resulting in abnormal.

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.8.1.RELEASE</version>
</dependency>

jar package Download: https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis
Here Insert Picture Description
to download the jar package imported into the engineering environment, RedisTemplate operating Redis so that you can use Spring provided, and just prior to use, solutions need to be explored for Spring provides, in order to make better use of them.

In most cases we will use a connection pool, so the first object is configured with a JedisPoolConfig Spring, this configuration is relatively simple, object code JedisPoolConfig Spring configuration shown below.

<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
    <!-- 最大空闲数 -->
    <property name="maxIdle" value="50" />
    <!-- 最大连接数 -->
    <property name="maxTotal" value="100" />
    <!-- 最大等待时间 -->
    <property name="maxWaitMillis" value="20000" />
</bean>

This sets up a connection pool configuration, continue down configuration.

Before using RedisTemplate Spring require configuration to provide connection factory provided by Spring, Spring Data Redis embodiment in which the plant model provides 4.
JredisConnectionFactory.
JedisConnectionFactory.
LettuceConnectionFactory.
SrpConnectionFactory.

虽然使用哪种实现工厂都是可以的,但是要根据环境进行测试,以验证使用哪个方案的性能是最佳的。无论如何它们都是接口 RedisConnectionFactory 的实现类,更多的时候我们都是通过接口定义去理解它们,所以它们是具有接口适用性特性的。本教程将以使用最为广泛的 JedisConnectionFactory 为例进行讲解。

例如,在 Spring 中配置一个 JedisConnectionFactory 对象,配置 JedisConnectionFactory 代码如下所示。

<bean id="connectionFactory"
    class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
    <property name="hostName" value="localhost" />
    <property name="port" value="6379" />
    <!--<property name="password" value="password"/> -->
    <property name="poolConfig" ref="poolConfig" />
</bean>

解释一下它的属性配置。
hostName,代表的是服务器,默认值是 localhost,所以如果是本机可以不配置它。
port,代表的是接口端口,默认值是 6379,所以可以使用默认的 Redis 端口,也可以不配置它。
password,代表的是密码,在需要密码连接 Redis 的场合需要配置它。
poolConfig,是连接池配置对象,可以设置连接池的属性。

这样就完成了一个 Redis 连接工厂的配置。这里配置的是 JedisConnectionFactory,如果需要的是 LettuceConnectionFactory,可以把使用 Spring 配置 JedisPoolConfig 对象代码中的 Bean 元素的 class 属性修改为 org.springframework.data.redis.connection.lettuce.LettuceConnectionFactor 即可,这取决于项目的需要和特殊性。有了 RedisConnectionFactory 工厂,就可以使用 RedisTemplate 了。

普通的连接使用没有办法把 Java 对象直接存入 Redis,而需要我们自己提供方案,这时往往就是将对象序列化,然后使用 Redis 进行存储,而取回序列化的内容后,在通过转换转变为 Java 对象,Spring 模板中提供了封装的方案,在它内部提供了 RedisSerializer 接口(org.springframework.data.redis.serializer.RedisSerializer)和一些实现类,其原理如下图所示:
Here Insert Picture Description
可以选择 Spring 提供的方案去处理序列化,当然也可以去实现在 spring data redis 中定义的 RedisSerializer 接口,在 Spring 中提供了以下几种实现 RedisSerializer 接口的序列化器。
GenericJackson2JsonRedisSerializer,通用的使用 Json2.jar 的包,将 Redis 对象的序列化器。
Jackson2JsonRedisSerializer,通过 Jackson2.jar 包提供的序列化进行转换(由于版本太旧,Spring 不推荐使用)。
JdkSerializationRedisSerializer,使用 JDK 的序列化器进行转化。
OxmSerializer,使用 Spring O/X 对象 Object 和 XML 相互转换。
StringRedisSerializer,使用字符串进行序列化。
GenericToStringSerializer,通过通用的字符串序列化进行相互转换。

使用它们就能够帮助我们把对象通过序列化存储到 Redis 中,也可以把 Redis 存储的内容转换为 Java 对象,为此 Spring 提供的 RedisTemplate 还有两个属性。
keySerializer——键序列器。
valueSerializer——值序列器。

有了上面的了解,就可以配置 RedisTemplate 了。假设选用 StringRedisSerializer 作为 Redis 的 key 的序列化器,而使用 JdkSerializationRedisSerializer 作为其 value 的序列化器,则可以以下代码的方法来配置 RedisTemplate。

<bean id="jdkSerializationRedisSerializer"
    class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
<bean id="stringRedisSerializer"
    class="org.springframework.data.redis.serializer.StringRedisSerializer" />
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="keySerializer" ref="stringRedisSerializer" />
    <property name="valueSerializer" ref="jdkSerializationRedisSerializer" />
</bean>

这样就配置了一个 RedisTemplate 的对象,并且 spring data redis 知道会用对应的序列化器去转换 Redis 的键值。

举个例子,新建一个角色对象,使用 Redis 保存它的对象,使用 Redis 保存角色类对象如下所示。

package com.pojo;
import java.io.Serializable;
public class Role implements Serializable {
    /**
     * 注意,对象要可序列化,需要实现Serializable接口,往往要重写serialVersionUID
     */
    private static final long serialVersionUID = 3447499459461375642L;
    private long id;
    private String roleName;
    private String note;
    //省略setter和getter方法
}

因为要序列化对象,所以需要实现 Serializable 接口,表明它能够序列化,而 serialVersionUID 代表的是序列化的版本编号。

接下来就可以测试保存这个 Role 对象了,测试代码如下所示。

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);
Role role = new Role();
role.setId(1L);
role.setRoleName("role_name_1");
role.setNote ("note_l");
redisTemplate.opsForValue().set("role_1", role);
Role role1 = (Role) redisTemplate.opsForValue().get ("role_1");
System.out.println(role1.getRoleName());

在 System.out.println(role1.getRoleName()) ;这行打下断点,可以看到如下图所示的测试结果。
Here Insert Picture Description
显然这里已经成功保存和获取了一个 Java 对象,这段代码演示的是如何使用 StringRedisSerializer 序列化 Redis 的 key,而使用 JdkSerializationRedisSerializer 序列化 Redis 的value,当然也可以根据需要去选择,甚至是自定义序列化器。

Note that the above are based on the use of RedisTemplate, connection pool based on the operation, in other words, does not guarantee that every time the operation is the same RedisTemplate Redis a connection, such as the following two lines of code in the code above. set and get method looks simple, it might come from a different connection with a Redis Redis connection pool.

In order to make all operations from the same connection, or may be used SessionCallback RedisCallback two interfaces, and is relatively low-RedisCallback package, using not very friendly, so that more time will SessionCallback use this interface, through this interface the plurality of commands can be placed in connection with a Redis to perform, as shown in the following code, which mainly realizes the functions of the above code.

package redisDemo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import com.pojo.Role;
public class Test {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        RedisTemplate<String, Role> redisTemplate = applicationContext.getBean(RedisTemplate.class);
        Role role = new Role();
        role.setId(1L);
        role.setRoleName("role_name_1");
        role.setNote("role_note_1");
        SessionCallback callBack = new SessionCallback<Role>() {
            @Override
            public Role execute(RedisOperations ops) throws DataAccessException {
                ops.boundValueOps("role_1").set(role);
                return (Role) ops.boundValueOps("role_1").get();
            }
        };
        Role savedRole = (Role) redisTemplate.execute(callBack);
        System.out.println(savedRole.getId());
    }
}

Such set and get commands can operate on the same guarantee in connection with a Redis a connection pool, here presented to the reader is to use an anonymous class, and in fact if Java JDK version 8, you can also use Lambda expressions SessionCallback write business logic, the logic of this will be more clear. Because of the connection are the same before and after use, so for resource consumption is relatively small, it will often be used when using Redis operating multiple commands or use a transaction.

Released five original articles · won praise 2 · Views 591

Guess you like

Origin blog.csdn.net/qq_42230770/article/details/104116665