SpringBoot实现Redis缓存

0. Redis安装

Windows下Redis的安装和使用

1. 引入依赖

pom文件

<!-- 引入Redis依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- commons-pool2 对象池依赖 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

2. 配置Redis

application.yml文件

spring:
  # Redis配置
  redis:
    # 超时时间
    timeout: 10000ms
    # 服务器地址
    host: 127.0.0.1
    # 服务器端口号
    port: 6379
    # 连接数据库
    database: 0
    password: 123456
    lettuce:
      pool:
        # 最大连接数
        max-active: 1024
        # 最大连接阻塞等待时间
        max-wait: 10000ms
        # 最大空闲连接
        max-idle: 200
        # 最小空闲连接
        min-idle: 5

3. 编写Redis配置类

package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author King
 * @description:
 * @create 2023-05-04-14:28-
 */
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory connectionFactory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        //String类型的key序列化器
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //String类型的value序列化器
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        //Hash类型的key序列化器
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        //Hash类型的value序列化器
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }
}

Tips:

Redis序列化Java8的LocalDate、LocalDateTime等时间类时会报错 在实体类的相应字段上添加两个注解@JsonDeserialize(using = LocalDateDeserializer.class)@JsonSerialize(using = LocalDateSerializer.class)就不会报错了

4. 编写Service方法

@Override
public List<Reservoir> selectReservoirAll() {
    //1.先在Redis中查找
    List<Reservoir> list = (List<Reservoir>) redisTemplate.opsForValue().get("shuiwen:reservoirAll:");
    //2.缓存未命中 去数据库中查 然后存入Redis缓存中
    if(list == null){
        //2.1 数据库中查
        list = reservoirMapper.selectReservoirAll();
        //2.2 写入Redis缓存
        redisTemplate.opsForValue().set("shuiwen:reservoirAll:", list);
    }
    return list;
}

猜你喜欢

转载自blog.csdn.net/IUUUUUUU/article/details/130493843