Spring Boot integration Lettuce Redis

SpringBoot To simplify the  Spring creation of applications, run, debug, deploy a range of issues such as the birth of the product, characteristics of the automatic assembly so that we can better focus on the business itself, rather than external XML configuration, we simply follow the norms related to the introduction of dependence can easily build a WEB project

Spring Boot In addition to supporting the common ORM framework, it is commonly used middleware to provide a very good package, with Spring Boot2.xthe arrival of support components become increasingly diverse, more and more mature, in which the Redissupport is not only enriched it of the API, it is to replace the underlying Jedisdependent instead replacedLettuce(生菜)

Redis Introduction

Redis is an open source use written in ANSI C, support network, based on the persistence of memory can log type, Key-Value database, and provides multi-lingual API. Compared to Memcachedits relatively more supported storage type (character, hash, sets, ordered sets, lists, GEO) , while Redis is thread-safe . Since March 15, 2010, Redis development work was hosted by VMware, 2013 began in May, Redis developed by the Pivotalsponsor.

Lettuce

Lettuce And  Jedis are connected to Redis Serverthe client program. JedisIn the implementation is directly connected redis server, multi-threaded environment, non-thread-safe, unless you are using a connection pool, increase physical connection for each instance of Jedis . LettuceBased Netty connection example of (StatefulRedisConnection), may concurrently access among multiple threads, and thread-safe, concurrent access to meet in a multithreaded environment, and it is scalable design, a connection instance can not be enough to increase demand connection instance .

Import dependence

In  pom.xml the spring-boot-starter-data-redisdependent, Spring Boot2.x the bottom is not Jedisif you do upgrade friends need attention under

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

Configuration Properties

In  application.properties the configuration file, the following, since Spring Boot2.x the changes required by the connection pool configuration spring.redis.lettuce.poolor the  spring.redis.jedis.pool configuration of the

spring.redis.host=localhost
spring.redis.password=battcn
# 连接超时时间(毫秒)
spring.redis.timeout=10000
# Redis默认情况下有16个分片,这里配置具体使用的分片,默认是0
spring.redis.database=0
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0

Specific coding

Spring BootOf Redissupport has been very perfect, good serialization and rich enough to deal with the daily API development

Entity class

Creating a Userclass

package com.battcn.entity;

import java.io.Serializable;

/**
 * @author Levin
 * @since 2018/5/10 0007
 */
public class User implements Serializable {

    private static final long serialVersionUID = 8655851615465363473L;
    private Long id;
    private String username;
    private String password;
    // TODO  省略get set
}

Custom Template

Under the default template can only support RedisTemplate&lt;String, String&gt;, that is only stored in the string, which is unfriendly, the custom template is necessary in development, when a custom template and want to use the Stringmemory This time we can use StringRedisTemplatethe way, they do not conflict ...

package com.battcn.config;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;

/**
 * TODO 修改database
 *
 * @author Levin
 * @since 2018/5/10 0022
 */
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisCacheAutoConfiguration {

    @Bean
    public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Serializable> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

test

Upon completion Preparation, writing a junittest class to test the correctness of the code, there are a lot of people questioned Redisthread safety, it also provides a test case the following response, if in doubt please correct me

package com.battcn;

import com.battcn.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.Serializable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/**
 * @author Levin
 * @since 2018/5/10 0010
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter8ApplicationTest {

    private static final Logger log = LoggerFactory.getLogger(Chapter8ApplicationTest.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;

    @Test
    public void get() {
        // TODO 测试线程安全
        ExecutorService executorService = Executors.newFixedThreadPool(1000);
        IntStream.range(0, 1000).forEach(i ->
                executorService.execute(() -> stringRedisTemplate.opsForValue().increment("kk", 1))
        );
        stringRedisTemplate.opsForValue().set("k1", "v1");
        final String k1 = stringRedisTemplate.opsForValue().get("k1");
        log.info("[字符缓存结果] - [{}]", k1);
        // TODO 以下只演示整合,具体Redis命令可以参考官方文档,Spring Data Redis 只是改了个名字而已,Redis支持的命令它都支持
        String key = "battcn:user:1";
        redisCacheTemplate.opsForValue().set(key, new User(1L, "u1", "pa"));
        // TODO 对应 String(字符串)
        final User user = (User) redisCacheTemplate.opsForValue().get(key);
        log.info("[对象缓存结果] - [{}]", user);
    }
}

Other types

The following is the Redisother type of operation corresponding

  • opsForValue:  corresponds String (String)
  • opsForZSet:  corresponds zset (ordered set)
  • opsForHash:  corresponding to Hash (hash)
  • opsForList:  corresponds List (List)
  • opsForSet:  corresponds Set (set)
  • opsForGeo:  corresponding to the GEO (Location)

to sum up

spring-data-redis document: https://docs.spring.io/spring-data/redis/docs/2.0.1.RELEASE/reference/html/#new-in-2.0.0
Redis Documentation: https://redis.io/documentation
Redis Chinese document: http://www.redis.cn/commands.html

At present, many chiefs have written about  SpringBoot  tutorial, and any similarity, please bear with me, this tutorial is based on the latest  spring-boot-starter-parent:2.0.1.RELEASEwritten, including the new version features will be introduced together

Guess you like

Origin blog.51cto.com/14230003/2413030