学无先后,达者为师

网站首页 编程语言 正文

Spring Cloud Loadbalancer 修改默认缓存为Caffeine,修改微服务启动关于Loadbalancer的WARN

作者:MateCloud微服务 更新时间: 2022-05-17 编程语言

一、背景描述

[mate-uaa:192.168.3.9:20001] 2022-01-22 23:27:52.907 WARN 17966 [] [main] iguration$LoadBalancerCaffeineWarnLogger : Spring Cloud LoadBalancer is currently working with the default cache. You can switch to using Caffeine cache, by adding it and org.springframework.cache.caffeine.CaffeineCacheManager to the classpath.

在微服务引入loadbalancer的包,如下所示:

<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-loadbalancerartifactId>
dependency>

默认情况下未做任何设置在启动的时候,就会出现篇首的告警信息。

二、建议优化

2.1 引入Caffeine依赖

<dependency>
    <groupId>com.github.ben-manes.caffeinegroupId>
    <artifactId>caffeineartifactId>
    <version>3.0.5version>
dependency>

2.2 项目中增加配置

spring:
  cloud:
	# 负载均衡器缓存
    loadbalancer:
      cache:
        enabled: true
        caffeine:
          spec: initialCapacity=500,expireAfterWrite=5s

2.3 自定义缓存配置代码(非必须)

package org.springframework.cloud.loadbalancer.cache;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.cloud.loadbalancer.core.CachingServiceInstanceListSupplier;
import org.springframework.util.StringUtils;

public class CaffeineBasedLoadBalancerCacheManager extends CaffeineCacheManager implements LoadBalancerCacheManager {
    public CaffeineBasedLoadBalancerCacheManager(String cacheName, LoadBalancerCacheProperties properties) {
        super(new String[]{cacheName});
        if (!StringUtils.isEmpty(properties.getCaffeine().getSpec())) {
            this.setCacheSpecification(properties.getCaffeine().getSpec());
        } else {
            this.setCaffeine(Caffeine.newBuilder().initialCapacity(properties.getCapacity()).expireAfterWrite(properties.getTtl()).softValues());
        }

    }

    public CaffeineBasedLoadBalancerCacheManager(LoadBalancerCacheProperties properties) {
        this(CachingServiceInstanceListSupplier.SERVICE_INSTANCE_CACHE_NAME, properties);
    }
}

其中

this.setCaffeine(Caffeine.newBuilder().initialCapacity(properties.getCapacity()).expireAfterWrite(properties.getTtl()).softValues());

就是使用默认的缓存配置信息对Caffeine进行配置

微服务平台推荐

matecloud微服务平台

原文链接:https://matecloud.blog.csdn.net/article/details/122645539

栏目分类
最近更新