导入maven坐标

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

配置yml

spring:
	redis:
    host: 127.0.0.2
    port: 6379
    password: 123456
    database: 0

需要配置序列化器(RedisConfig)

//默认的Key序列化器为:JdkSerializationRedisSerializer

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();

        //默认的Key序列化器为:JdkSerializationRedisSerializer
        redisTemplate.setKeySerializer(new StringRedisSerializer()); // key序列化
        //redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); // value序列化

        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }
}

实际运用(例子)

首先要在需要使用缓存的类中注入RedisTemplate 这个bean是SpringBoot自动装配的。

		@Autowired
    private RedisTemplate redisTemplate;

保存keyemail和value code ,设置缓存时间2分钟

redisTemplate.opsForValue().set(email,code,2, TimeUnit.MINUTES);

删除key为email的缓存

redisTemplate.delete(email);

拼接key后,获取这个key的缓存

				//动态构造key
        String key ="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);