SpringBoot使用分布式缓存

如果对SpringBoot缓存不熟悉的建议先看第一片文章SpringBoot使用caffeine作为缓存,为什么使用分布式缓存?在实际开发场景中,往往单机应用无法满足当前的需求,需要对项目进行分布式部署,由此,每个项目中的缓存都是属于自己独立服务的,并不能共享,其次,当某个服务更新了缓存,其他服务并不知道,当用户请求到其他服务时,获取到的往往还是旧的数据,说到这,就有人会说使用Redis进行代替,但是Redis毕竟是借助于第三方,会存在网络消耗,如果所有都堆积到Redis,会造成Redis被大量并发访问,最坏会被宕机,所以我们可以使用本地缓存和Redis缓存结合进行使用,运用Redis的发布订阅功能进行通知其他服务更新缓存.

接下来简单介绍本人开源的一个分布式缓存使用方法

一. 引入依赖

<dependency>
    <groupId>cn.gjing</groupId>
    <artifactId>tools-redis</artifactId>
    <version>1.0.0</version>
</dependency>

二. 启动类标上注解

/**
 * @author Gjing
 */
@SpringBootApplication
@EnableSecondCache
public class TestRedisApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestRedisApplication.class, args);
    }
}

三. 配置

  • 配置参数

1. Set cacheNames:缓存key名称
2. boolean cacheValueNullable:是否存储控制,默认true,防止缓存穿透
3. boolean dynamic:是否动态根据cacheName创建Cache实现
4. String cachePrefix:默认无
5. Integer expire:redis缓存过期时间,单位秒
6. Map everyCacheExpire:每个cacheName的过期时间,单位秒,优先级比defaultExpiration高
7. String topic:缓存更新时通知其他节点的topic名称
8. Integer expireAfterAccess:访问后过期时间,默认不过期,单位毫秒
9. Integer expireAfterWrite:写入后过期时间,默认不过期,单位毫秒
10. Integer refreshAfterWrite:写入后刷新时间,默认不过期,单位毫秒
11. Integer initialCapacity:初始化大小
12. Integer maximumSize:最大缓存对象个数,超过此数量时之前放入的缓存将失效

  • yml方式
second:
  cache:
    cache-prefix: 锁的前缀
    redis:
      expire: 10
    caffeine:
      expire-after-write: 3000
  • JavaBean方式
/**
 * @author Gjing
 **/
@Configuration
public class CacheConfiguration {

    @Bean
    public SecondCache secondCache() {
        return SecondCache.builder()
                .cachePrefix("锁的前缀")
                .dynamic(true)
                .build();
    }

    @Bean
    public RedisCache redisCache() {
        return RedisCache.builder()
                .expire(10)
                .build();
    }

    @Bean
    public CaffeineCache caffeineCache() {
        return CaffeineCache.builder()
                .expireAfterWrite(3000)
                .build();
    }
}

四. 简单使用

/**
 * @author Gjing
 **/
@Service
@Slf4j
public class CustomService {

    @Resource
    private CustomRepository customRepository;

    /**
     * 获取一个用户
     * @param customId 用户id
     * @return Custom
     */
    @Cacheable(value = "user",key = "#customId")
    public Custom getCustom(Integer customId) {
        log.warn("查询数据库用户信息");
        return customRepository.findById(customId).orElseThrow(() -> new NullPointerException("User is not exist"));
    }

    /**
     * 删除一个用户
     * @param customId 用户id
     */
    @CacheEvict(value = "user", key = "#customId")
    public void deleteUser(Integer customId) {
        Custom custom = customRepository.findById(customId).orElseThrow(() -> new NullPointerException("User is not exist"));
        customRepository.delete(custom);
    }
}

五. 定义接口调用

/**
 * @author Gjing
 **/
@RestController
public class CustomController {
    @Resource
    private CustomService customService;

    @GetMapping("/user/{custom-id}")
    @ApiOperation(value = "查询用户",httpMethod = "GET")
    public ResponseEntity getUser(@PathVariable("custom-id") Integer customId) {
        return ResponseEntity.ok(customService.getCustom(customId));
    }

    @DeleteMapping("/user")
    @ApiOperation(value = "删除用户", httpMethod = "DELETE")
    @ApiImplicitParam(name = "customId", value = "用户Id", dataType = "int", required = true, paramType = "Query")
    @NotNull
    public ResponseEntity deleteUser(Integer customId) {
        customService.deleteUser(customId);
        return ResponseEntity.ok("Successfully delete");
    }
}

调用结果

res

使用中如果有任何问题,欢迎评论留言,我会及时回复以及更新

猜你喜欢

转载自yq.aliyun.com/articles/706643
今日推荐