Spring Cloud Loadbalancer 修改默认缓存为Caffeine,修改微服务启动关于Loadbalancer的WARN
Posted MateCloud微服务
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Cloud Loadbalancer 修改默认缓存为Caffeine,修改微服务启动关于Loadbalancer的WARN相关的知识,希望对你有一定的参考价值。
一、背景描述
[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.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
默认情况下未做任何设置在启动的时候,就会出现篇首的告警信息。
二、建议优化
2.1 引入Caffeine依赖
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.0.5</version>
</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进行配置
微服务平台推荐
以上是关于Spring Cloud Loadbalancer 修改默认缓存为Caffeine,修改微服务启动关于Loadbalancer的WARN的主要内容,如果未能解决你的问题,请参考以下文章
Spring Cloud Loadbalancer 修改默认缓存为Caffeine,修改微服务启动关于Loadbalancer的WARN
SpringCloud升级之路-2020.0.x - 6.使用 Spring Cloud LoadBalancer
SpringCloud升级之路-2020.0.x - 6.使用 Spring Cloud LoadBalancer