springboot使用@EnableCaching实现缓存

项目中我们对于不易改动的信息没必要每次都去数据库查询,可以将查询结果放入缓存中,第二次调用时,直接在缓存中获取,不再经过数据库

1:配置cacheManager类

@EnableCaching
@Configuration
public class CacheConfig {
    
    @Bean
    public ConcurrentMapCacheManager cacheManager() {
        ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager();
        //cacheManager.setStoreByValue(true); //true表示缓存一份副本,否则缓存引用
        return cacheManager;
    }

}

2:controller层代码:

@Cacheable(cacheNames = "studentCache", key = "#id")
@GetMapping("/get/one")
@ApiOperation(value="查询单条记录",notes = "查询")
//@ApiImplicitParam(name="id",defaultValue ="", value = "主键id",required = true,dataType ="Integer" )
public Student getOneInfo(@RequestParam(value = "id",defaultValue = "")@ApiParam(value="主键id") Integer id){
    Student student=null;
    try {
        //int i=1/0;
        Date date=new Date();
        System.out.println("进行了查询---》"+ date.getTime());
        student= studentService.selectOne(id);
    } catch (Exception e) {
        throw ServiceException.zero_exception;
    }
    return student;
}

分析:
@Cacheable---------》开启缓存注解
studentCache---------》缓存名称
key---------》缓存的key值
方法的返回值---------》缓存的value值

通过查看缓存的信息可知,缓存放入成功:

@GetMapping("/get/cache")
@ApiOperation(value="查看缓存信息")
public String getCache(){
    Cache demoCache = cacheManager.getCache("studentCache");
    System.out.println(demoCache.getName());
    System.out.println(demoCache.get(1, Student.class));
    return demoCache.getName();
}

接下来,我们将缓存替换成redis缓存:

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@EnableCaching
@Configuration
public class CacheConfig {

    /*@Bean
    public ConcurrentMapCacheManager cacheManager() {
        ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager();
        //cacheManager.setStoreByValue(true); //true表示缓存一份副本,否则缓存引用
        return cacheManager;
    }*/

    /**
     * 最新版,设置redis缓存过期时间
     */

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        return new RedisCacheManager(
                RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
                this.getRedisCacheConfigurationWithTtl( 60), // 默认策略,未配置的 key 会使用这个
                this.getRedisCacheConfigurationMap() // 指定 key 策略
        );
    }

    private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
        Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
        //SsoCache和BasicDataCache进行过期时间配置
        redisCacheConfigurationMap.put("messagCache", this.getRedisCacheConfigurationWithTtl(30 * 60));

        //自定义设置缓存时间
        redisCacheConfigurationMap.put("studentCache", this.getRedisCacheConfigurationWithTtl(60 ));

        return redisCacheConfigurationMap;
    }

    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
                RedisSerializationContext
                        .SerializationPair
                        .fromSerializer(jackson2JsonRedisSerializer)
        ).entryTtl(Duration.ofSeconds(seconds));

        return redisCacheConfiguration;
    }

}

使用RedisConnectionFactory 生成 cacheManager 对象,其余保持一致

controller:

@Cacheable(cacheNames = "studentCache", key = "#id")
@GetMapping("/get/one")
@ApiOperation(value="查询单条记录",notes = "查询")
//@ApiImplicitParam(name="id",defaultValue ="", value = "主键id",required = true,dataType ="Integer" )
public Student getOneInfo(@RequestParam(value = "id",defaultValue = "")@ApiParam(value="主键id") Integer id){
    Student student=null;
    try {
        //int i=1/0;
        Date date=new Date();
        System.out.println("进行了查询---》"+ date.getTime());
        student= studentService.selectOne(id);
    } catch (Exception e) {
        throw ServiceException.zero_exception;
    }
    return student;
}

查看缓存信息:

@GetMapping("/get/redis/cache")
@ApiOperation(value="查看redis缓存信息")
public String getRedisCache(){
    Cache demoCache = redisCacheManager.getCache("studentCache");
    System.out.println(demoCache.getName());
    System.out.println(demoCache.get(1, Student.class));
    return demoCache.getName();
}

调用查看缓存:
在这里插入图片描述
一分钟缓存时间到后,缓存清空:
在这里插入图片描述

  • 15
    点赞
  • 62
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot是一个开发框架,它简化了使用Spring框架进行Java应用程序开发的过程。Redis是一个内存数据结构存储系统,它可以用作缓存和数据库。@Cacheable是Spring框架的注解之一,它可以用于缓存方法的返回值。 要在Spring Boot中使用Redis和@Cacheable来实现缓存,首先需要配置Redis连接。可以通过在`application.properties`或`application.yml`文件中添加以下配置来完成: ```yaml spring.redis.host=127.0.0.1 spring.redis.port=6379 ``` 接下来,在需要缓存的方法上使用`@Cacheable`注解。例如,假设我们有一个名为`getUserById`的方法,用于根据用户ID获取用户信息: ```java @Service public class UserService { @Cacheable(value = "users", key = "#id") public User getUserById(Long id) { // 从数据库或其他数据源获取用户信息 return userRepository.findById(id); } } ``` 在上述示例中,`@Cacheable`注解用于将方法的返回值缓存起来。其中,`value`属性指定了缓存的名称,`key`属性指定了缓存的键。在这个例子中,缓存的名称为"users",缓存的键为方法的参数id。 最后,需要在Spring Boot应用程序的启动类上添加`@EnableCaching`注解来启用缓存功能: ```java @SpringBootApplication @EnableCaching public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 以上就是使用Spring Boot、Redis和@Cacheable实现缓存的基本步骤。通过配置Redis连接,使用`@Cacheable`注解来标记需要缓存的方法,并在启动类上添加`@EnableCaching`注解来启用缓存功能,可以轻松地实现缓存功能。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值