springcloud ribbon 客户端负载均衡用法

博客记录了处理主机名不识别问题的过程。最初怀疑主机名未在系统文件hosts中配置,检查后排除。后发现使用Ribbon时,需在RestTemplate bean配置中添加负载均衡注解@LoadBalanced,并给出了相应的配置代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://DEPT-8001/dept/get/1": DEPT-8001; nested exception is java.net.UnknownHostException: DEPT-8001
 

不识别主机名称、则可能是主机名称没在系统文件hosts中配置,但检查发现,已经配置,排除。

于是查了一下Ribbon的用法,发现使用Ribbon的时候,必须要在RestTemplate bean配置中添加负载均衡注解@LoadBalanced

于是加完如下:

package com.zemel.consumer.config;

import java.nio.charset.Charset;
import java.util.Base64;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestConfig {

@Bean
public HttpHeaders getHeaders(){
// 进行一个Http头信息配置
HttpHeaders headers = new HttpHeaders();
String auth = "wendy:wendy";
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(Charset.forName("US-ASCII")));
// 加密字符串要有空格
String authHeader = "Basic " + new String(encodedAuth);

headers.set("Authorization", authHeader);
return headers;
}

@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}


}

转载于:https://www.cnblogs.com/liuys635/p/10546131.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值