• notice
  • Congratulations on the launch of the Sought Tech site

Using Redis database in Spring Boot

In addition to providing excellent automation support for commonly used relational databases, Spring Boot also provides automatic configuration support for many NoSQL databases, including: Redis, MongoDB, Elasticsearch, Solr and Cassandra.

Using Redis

Redis is an open source log-type, key-value database written in ANSI C language, supporting network, and being memory-based and persistent.

  • Redis official website

  • Redis Chinese Community

import dependencies

Spring Data Redis, the data access framework provided by Spring Boot, is based on Jedis. spring-boot-starter-redisDependencies can be configured by importing

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

parameter configuration

application.propertiesAdd the relevant configuration of the Redis server in accordance with the usual practice , the details are as follows:

# REDIS (RedisProperties)# Redis数据库索引(默认为0)spring.redis.database=0# Redis服务器地址spring.redis.host=localhost# Redis服务器连接端口spring.redis.port=6379# Redis服务器连接密码(默认为空)spring.redis.password=# 连接池最大连接数(使用负值表示没有限制)spring.redis.pool.max-active=8# 连接池最大阻塞等待时间(使用负值表示没有限制)spring.redis.pool.max-wait=-1# 连接池中的最大空闲连接spring.redis.pool.max-idle=8# 连接池中的最小空闲连接spring.redis.pool.min-idle=0# 连接超时时间(毫秒)spring.redis.timeout=0

The configuration of spring.redis.database usually uses 0. Redis can set the number of databases when configuring. The default is 16, which can be understood as the schema of the database.

 

test access

Illustrate how to access Redis by writing test cases.

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)public class ApplicationTests { @Autowired
private StringRedisTemplate stringRedisTemplate; @Test
public void test() throws Exception { // 保存字符串
stringRedisTemplate.opsForValue().set("aaa", "111");
Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));
   }}

The above very simple test case demonstrates how to StringRedisTemplateread and write Redis through an automatically configured object. From the name, you can notice that the object supports the String type. If developers who have used spring-data-redis must be familiar with the RedisTemplate<K, V>interface, StringRedisTemplateit is equivalent to RedisTemplate<String, String>the implementation.

 

In addition to the String type, we often store objects in Redis in practice. At this time, we will wonder whether we can use something similar RedisTemplate<String, User>to initialize and operate. However, Spring Boot does support direct use. We need to implement the interface ourselves RedisSerializer<T>to serialize and deserialize the incoming object. Next, we use an instance to complete the read and write operations of the object.

  • Create the object to store: User

    public class User implements Serializable {    private static final long serialVersionUID = -1L;    private String username;    private Integer age;    public User(String username, Integer age) {        this.username = username;        this.age = age;
       }
       // 省略getter和setter}

     

  • Implement the serialization interface of the object

    public class RedisObjectSerializer implements RedisSerializer<Object> {  private Converter<Object, byte[]> serializer = new SerializingConverter();  private Converter<byte[], Object> deserializer = new DeserializingConverter();  static final byte[] EMPTY_ARRAY = new byte[0];  public Object deserialize(byte[] bytes) {    if (isEmpty(bytes)) {      return null;
       }
       try {      return deserializer.convert(bytes);
       } catch (Exception ex) {      throw new SerializationException("Cannot deserialize", ex);
       }
     }
     public byte[] serialize(Object object) {    if (object == null) {      return EMPTY_ARRAY;
       }
       try {      return serializer.convert(object);
       } catch (Exception ex) {      return EMPTY_ARRAY;
       }
     }
     private boolean isEmpty(byte[] data) {    return (data == null || data.length == 0);
     }}

     

  • Configure a RedisTemplate instance for User

    @Configurationpublic class RedisConfig {    @Bean
       JedisConnectionFactory jedisConnectionFactory() {        return new JedisConnectionFactory();
       }
       @Bean
       public RedisTemplate<String, User> redisTemplate(RedisConnectionFactory factory) {
           RedisTemplate<String, User> template = new RedisTemplate<String, User>();
           template.setConnectionFactory(jedisConnectionFactory());
           template.setKeySerializer(new StringRedisSerializer());
           template.setValueSerializer(new RedisObjectSerializer());        return template;
       }}

     

Of course, the data operations provided in spring-data-redis are far more than these. This article is only used as a configuration reference when using redis in Spring Boot. For more operations on redis, please refer to Spring-data-redis Reference.


Tags

Technical otaku

Sought technology together

Related Topic

0 Comments

Leave a Reply

+