Spring Cloud Eureka使用服务名调用接口报Illegal character错误咨询
问题解决方案
1. 修复URL字符串的非法字符
你抛出Illegal character in authority报错的直接原因是代码中的请求URL字符串被人为换行加缩进,引入了多余的不可见空格:
// 错误写法:字符串拆分换行后带入大量空格,拼接后实际为 http://contact- service/xxx 包含非法空格 List contacts = this.resttemplate.getForObject("http://contact- service/contact/"+user.getUserId(),List.class);
调整为无多余空格的完整写法即可:
List contacts = this.resttemplate.getForObject("http://contact-service/contact/"+user.getUserId(),List.class);
2. 给RestTemplate添加@LoadBalanced注解
要实现通过Eureka注册的服务名发起调用,必须给RestTemplate开启负载均衡能力,否则Spring无法将服务名自动解析为对应的实例地址。你需要在配置类中声明RestTemplate Bean时添加对应注解:
import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class RestTemplateConfig { @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } }
注:如果之前是通过其他方式注入RestTemplate,需要确保使用的Bean携带@LoadBalanced注解。
3. 补全Eureka客户端配置
你当前的两个微服务都缺少必要的Eureka客户端配置,无法正常从Eureka Server拉取服务注册列表:
用户服务application.properties补充配置:
eureka.client.fetch-registry=true eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
联系人服务application.properties补充配置:
eureka.client.fetch-registry=true eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
4. 验证排查
- 启动所有服务后,访问Eureka控制台
http://localhost:8761,确认user-service和contact-service都出现在注册列表中 - 确认联系人服务的接口路径确实为
/contact/{userId},返回值结构匹配List类型
内容的提问来源于stack exchange,提问作者Satyam saxena
相关产品推荐
相关产品推荐

