目录

1.导入依赖

2.配置yaml文件

3.创建CacheConfig类

4.创建UserDTO和AdminUserDTO

5.创建UserController类

 6.测试结果

7.总结


1.导入依赖

    implementation 'com.github.ben-manes.caffeine:caffeine:3.0.6'
    implementation 'org.springframework.boot:spring-boot-starter-cache'
    implementation 'org.springframework.boot:spring-boot-configuration-processor'

2.配置yaml文件

cache-config:
  specs:
    user:
      # 过期时间
      expire-time: 10
      # 缓存最大数量
      max-size: 200
    admin:
      expire-time: 20
      max-size: 200

3.创建CacheConfig类

@Slf4j
@Data
@Configuration
@ConfigurationProperties("cache-config")
public class CacheConfig {

    private Map<String, CacheSpec> specs;

    @Data
    public static class CacheSpec {
        private Integer expireTime;
        private Integer maxSize;
    }

    @Bean
    public CacheManager cacheManager(Ticker ticker) {
        SimpleCacheManager manager = new SimpleCacheManager();
        if (specs != null) {
            List<CaffeineCache> caches =
                    specs.entrySet().stream()
                            .map(entry -> buildCache(entry.getKey(),
                                    entry.getValue(),
                                    ticker))
                            .collect(Collectors.toList());
            manager.setCaches(caches);
        }
        return manager;
    }

    private CaffeineCache buildCache(String name, CacheConfig.CacheSpec cacheSpec, Ticker ticker) {
        final Caffeine<Object, Object> caffeineBuilder
                = Caffeine.newBuilder()
                .expireAfterWrite(cacheSpec.getExpireTime(), TimeUnit.SECONDS)
                .maximumSize(cacheSpec.getMaxSize())
                .ticker(ticker);
        return new CaffeineCache(name, caffeineBuilder.build());
    }

    @Bean
    public Ticker ticker() {
        return Ticker.systemTicker();
    }
}

4.创建UserDTO和AdminUserDTO

@Data
@Builder(toBuilder = true)
@NoArgsConstructor
@AllArgsConstructor
public class UserDTO {

    private Long id;

    private String name;
}
@Data
@Builder(toBuilder = true)
@NoArgsConstructor
@AllArgsConstructor
public class AdminUserDTO {

    private Long id;

    private String name;
}

5.创建UserController类

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Cacheable("user")
    @GetMapping
    public UserDTO getUser() {
        log.info("没走缓存");
        return UserDTO.builder()
                .id(1L)
                .name("张三")
                .build();
    }

    @Cacheable("admin")
    @GetMapping("/admin")
    public AdminUserDTO getAdminUser() {
        log.info("没走缓存");
        return AdminUserDTO.builder()
                .id(2L)
                .name("李四")
                .build();
    }
}

 6.测试结果

启动项目测试两个接口,我们到以下结论:

  1. 两个接口第一都打印了“没走缓存”日志,实际当中相当于都去查库了,第二次访问的时候发现两个接口都没打印日志,说明两个接口都走缓存了。
  2. 等10秒后我们访问getUser()接口发现再次打印了“没走缓存”日志,说明缓存过期时间是10秒。
  3. 等10秒后我们访问getAdminUser()接口发现没有打印了“没走缓存”日志,说明两个接口的缓存过期时间不同。
  4. 等20秒后我们访问getAdminUser()接口发现打印了“没走缓存”日志,说明该接口缓存过期时间是20秒。

7.总结

我们是通过配置文件设置不同缓存过期时间,这样的好处可以根据项目实际需求设置本地缓存时长。如果我们需要比较实时的一些数据,我们就可以把缓存时间设置短点,如果我们能容许数据没那么实时,就可以把缓存时间设置长点

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐