REmote DIctionary Server(Redis) is a key-value storage system written by Salvatore Sanfilippo. Redis is an open source, network-enabled, memory-based and persistent logging, key-value database written in ANSI C, BSD compliant, and provides multiple language apis. It is often referred to as a data structure server because values can be strings, hashes, lists, collections, and ordered collections.

Add the dependent

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

The configuration file

spring:
  redis:
    host: localhost
    database: 0
    port: 6379
    timeout: 3000
Copy the code

Configure the serialization mode

@Configuration
public class LettuceRedisConfiguration {
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        returnredisTemplate; }}Copy the code

Test the

@SpringBootTest
@RunWith(SpringRunner.class)
public class RedisTemplateTest {
    @Resource
    private RedisTemplate<String, User> redisTemplate;
    @Test
    public void redisTemplateTest(a) {
        redisTemplate.opsForValue().set("USER".new User(1L."Vincent"."Jiang"));
        User user = redisTemplate.opsForValue().get("USER");
        Assert.assertNotNull(user);
        Assert.assertEquals(user.getId().longValue(), 1L);
        Assert.assertEquals(user.getFirstName(), "Vincent");
        Assert.assertEquals(user.getLastName(), "Jiang"); }}Copy the code