发布于 3年前

Spring Cloud集成ZooKeeper注册中心绑定指定ip,解决UnknownHostException

Spring Cloud集成Zookeeper作为注册中心,从网关Spring Cloud GateWay转发给微服务里,在微服务里看到发送请求过来是以主机别名为url,如主机别名是server1.cluster,那么访问的地址是http://server.cluster/xxx 。在GateWay有时会导致找不到服务。报类似如下的错误:

500 Server Error for HTTP GET "/users/10/profile"
java.net.UnknownHostException: server.cluster
        at java.net.InetAddress.getAllByName0(InetAddress.java:1280) ~[?:1.8.0_151]
        Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
Error has been observed at the following site(s):
        |_ checkpoint 鈬org.springframework.cloud.gateway.filter.WeightCalculatorWebFilter [DefaultWebFilterChain]
        |_ checkpoint 鈬com.ubtech.security.gateway.filter.GatewayMainFilter [DefaultWebFilterChain]
        |_ checkpoint 鈬com.ubtech.security.gateway.filter.CacheBodyGlobalFilter [DefaultWebFilterChain]
        |_ checkpoint 鈬HTTP GET "/users/10/profile" [ExceptionHandlingWebHandler]
Stack trace:
                at java.net.InetAddress.getAllByName0(InetAddress.java:1280) ~[?:1.8.0_151]
                at java.net.InetAddress.getAllByName(InetAddress.java:1192) ~[?:1.8.0_151]
                at java.net.InetAddress.getAllByName(InetAddress.java:1126) ~[?:1.8.0_151]
                at java.net.InetAddress.getByName(InetAddress.java:1076) ~[?:1.8.0_151]
                at io.netty.util.internal.SocketUtils$8.run(SocketUtils.java:148) ~[netty-all-4.1.45.Final.jar!/:4.1.45.Final]

解决方法是向zookeeper注册服务时,指定服务的地址,示例:

spring.cloud.zookeeper.connectString=192.168.1.110:2181    #zookeeper地址
spring.cloud.zookeeper.discovery.instanceHost=192.168.2.11  #绑定的ip
spring.cloud.zookeeper.discovery.instancePort=8888          #绑定的端口
©2020 edoou.com   京ICP备16001874号-3