springcloud ribbon 客户端负载均衡用法

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();
}


}

posted @   技术研究与问题解决  阅读(246)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示