zoukankan      html  css  js  c++  java
  • springcloud-alibaba手写负载均衡的坑,采用restTemplate,不能添加@loadbalanced注解,否则采用了robbin

    采用springcloud-alibaba整合rabbion使用DiscoveryClient调用restful时遇到的一个问题,报错如下:

      1 D:javaDevlepTooljava1.8jdk1.8injava.exe -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-javaagent:D:javaDevlepToolIDEAIntelliJ IDEA 2018.2.8libidea_rt.jar=57241:D:javaDevlepToolIDEAIntelliJ IDEA 2018.2.8in" -Dfile.encoding=UTF-8 -classpath D:javaDevlepTooljava1.8jdk1.8jrelibcharsets.jar;D:javaDevlepTooljava1.8jdk1.8jrelibdeploy.jar;D:javaDevlepTooljava1.8jdk1.8jrelibextaccess-bridge-64.jar;D:javaDevlepTooljava1.8jdk1.8jrelibextcldrdata.jar;D:javaDevlepTooljava1.8jdk1.8jrelibextdnsns.jar;D:javaDevlepTooljava1.8jdk1.8jrelibextjaccess.jar;D:javaDevlepTooljava1.8jdk1.8jrelibextjfxrt.jar;D:javaDevlepTooljava1.8jdk1.8jrelibextlocaledata.jar;D:javaDevlepTooljava1.8jdk1.8jrelibext
    ashorn.jar;D:javaDevlepTooljava1.8jdk1.8jrelibextsunec.jar;D:javaDevlepTooljava1.8jdk1.8jrelibextsunjce_provider.jar;D:javaDevlepTooljava1.8jdk1.8jrelibextsunmscapi.jar;D:javaDevlepTooljava1.8jdk1.8jrelibextsunpkcs11.jar;D:javaDevlepTooljava1.8jdk1.8jrelibextzipfs.jar;D:javaDevlepTooljava1.8jdk1.8jrelibjavaws.jar;D:javaDevlepTooljava1.8jdk1.8jrelibjce.jar;D:javaDevlepTooljava1.8jdk1.8jrelibjfr.jar;D:javaDevlepTooljava1.8jdk1.8jrelibjfxswt.jar;D:javaDevlepTooljava1.8jdk1.8jrelibjsse.jar;D:javaDevlepTooljava1.8jdk1.8jrelibmanagement-agent.jar;D:javaDevlepTooljava1.8jdk1.8jrelibplugin.jar;D:javaDevlepTooljava1.8jdk1.8jrelib
    esources.jar;D:javaDevlepTooljava1.8jdk1.8jrelib
    t.jar;D:drawnbluespringcloud-alibabauser	argetclasses;D:javaEnvironment
    epoorgspringframeworkootspring-boot-starter-web2.1.6.RELEASEspring-boot-starter-web-2.1.6.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworkootspring-boot-starter-json2.1.6.RELEASEspring-boot-starter-json-2.1.6.RELEASE.jar;D:javaEnvironment
    epocomfasterxmljacksoncorejackson-databind2.9.9jackson-databind-2.9.9.jar;D:javaEnvironment
    epocomfasterxmljacksoncorejackson-annotations2.9.0jackson-annotations-2.9.0.jar;D:javaEnvironment
    epocomfasterxmljacksoncorejackson-core2.9.9jackson-core-2.9.9.jar;D:javaEnvironment
    epocomfasterxmljacksondatatypejackson-datatype-jdk82.9.9jackson-datatype-jdk8-2.9.9.jar;D:javaEnvironment
    epocomfasterxmljacksondatatypejackson-datatype-jsr3102.9.9jackson-datatype-jsr310-2.9.9.jar;D:javaEnvironment
    epocomfasterxmljacksonmodulejackson-module-parameter-names2.9.9jackson-module-parameter-names-2.9.9.jar;D:javaEnvironment
    epoorgspringframeworkootspring-boot-starter-tomcat2.1.6.RELEASEspring-boot-starter-tomcat-2.1.6.RELEASE.jar;D:javaEnvironment
    epoorgapache	omcatembed	omcat-embed-core9.0.21	omcat-embed-core-9.0.21.jar;D:javaEnvironment
    epoorgapache	omcatembed	omcat-embed-el9.0.21	omcat-embed-el-9.0.21.jar;D:javaEnvironment
    epoorgapache	omcatembed	omcat-embed-websocket9.0.21	omcat-embed-websocket-9.0.21.jar;D:javaEnvironment
    epoorghibernatevalidatorhibernate-validator6.0.17.Finalhibernate-validator-6.0.17.Final.jar;D:javaEnvironment
    epojavaxvalidationvalidation-api2.0.1.Finalvalidation-api-2.0.1.Final.jar;D:javaEnvironment
    epoorgjbossloggingjboss-logging3.3.2.Finaljboss-logging-3.3.2.Final.jar;D:javaEnvironment
    epocomfasterxmlclassmate1.4.0classmate-1.4.0.jar;D:javaEnvironment
    epoorgspringframeworkspring-web5.1.8.RELEASEspring-web-5.1.8.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworkspring-beans5.1.8.RELEASEspring-beans-5.1.8.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworkspring-webmvc5.1.8.RELEASEspring-webmvc-5.1.8.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworkspring-aop5.1.8.RELEASEspring-aop-5.1.8.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworkspring-context5.1.8.RELEASEspring-context-5.1.8.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworkspring-expression5.1.8.RELEASEspring-expression-5.1.8.RELEASE.jar;D:javaEnvironment
    epoorgslf4jslf4j-api1.7.26slf4j-api-1.7.26.jar;D:javaEnvironment
    epoorgspringframeworkspring-core5.1.8.RELEASEspring-core-5.1.8.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworkspring-jcl5.1.8.RELEASEspring-jcl-5.1.8.RELEASE.jar;D:drawnbluespringcloud-alibabacommon	argetclasses;D:javaEnvironment
    epoorgspringframeworkcloudspring-cloud-starter-alibaba-nacos-discovery.9.0.RELEASEspring-cloud-starter-alibaba-nacos-discovery-0.9.0.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworkcloudspring-cloud-alibaba-nacos-discovery.9.0.RELEASEspring-cloud-alibaba-nacos-discovery-0.9.0.RELEASE.jar;D:javaEnvironment
    epocomalibaba
    acos
    acos-client1.0.0
    acos-client-1.0.0.jar;D:javaEnvironment
    epocomalibaba
    acos
    acos-common1.0.0
    acos-common-1.0.0.jar;D:javaEnvironment
    epocommons-iocommons-io2.2commons-io-2.2.jar;D:javaEnvironment
    epoorgapachecommonscommons-lang33.8.1commons-lang3-3.8.1.jar;D:javaEnvironment
    epocomalibaba
    acos
    acos-api1.0.0
    acos-api-1.0.0.jar;D:javaEnvironment
    epocomalibabafastjson1.2.47fastjson-1.2.47.jar;D:javaEnvironment
    epocomgoogleguavaguava19.0guava-19.0.jar;D:javaEnvironment
    epocommons-codeccommons-codec1.11commons-codec-1.11.jar;D:javaEnvironment
    epoioprometheussimpleclient.5.0simpleclient-0.5.0.jar;D:javaEnvironment
    epoorgspringframeworkcloudspring-cloud-commons2.1.2.RELEASEspring-cloud-commons-2.1.2.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworksecurityspring-security-crypto5.1.5.RELEASEspring-security-crypto-5.1.5.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworkcloudspring-cloud-context2.1.2.RELEASEspring-cloud-context-2.1.2.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworkcloudspring-cloud-starter-netflix-ribbon2.1.2.RELEASEspring-cloud-starter-netflix-ribbon-2.1.2.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworkcloudspring-cloud-starter2.1.2.RELEASEspring-cloud-starter-2.1.2.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworksecurityspring-security-rsa1.0.7.RELEASEspring-security-rsa-1.0.7.RELEASE.jar;D:javaEnvironment
    epoorgouncycastlecpkix-jdk15on1.60cpkix-jdk15on-1.60.jar;D:javaEnvironment
    epoorgouncycastlecprov-jdk15on1.60cprov-jdk15on-1.60.jar;D:javaEnvironment
    epoorgspringframeworkcloudspring-cloud-netflix-ribbon2.1.2.RELEASEspring-cloud-netflix-ribbon-2.1.2.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworkcloudspring-cloud-netflix-archaius2.1.2.RELEASEspring-cloud-netflix-archaius-2.1.2.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworkcloudspring-cloud-starter-netflix-archaius2.1.2.RELEASEspring-cloud-starter-netflix-archaius-2.1.2.RELEASE.jar;D:javaEnvironment
    epocom
    etflixarchaiusarchaius-core.7.6archaius-core-0.7.6.jar;D:javaEnvironment
    epocomgooglecodefindbugsjsr3053.0.1jsr305-3.0.1.jar;D:javaEnvironment
    epocommons-configurationcommons-configuration1.8commons-configuration-1.8.jar;D:javaEnvironment
    epocom
    etflix
    ibbon
    ibbon2.3.0
    ibbon-2.3.0.jar;D:javaEnvironment
    epocom
    etflix
    ibbon
    ibbon-transport2.3.0
    ibbon-transport-2.3.0.jar;D:javaEnvironment
    epoio
    eactivex
    xnetty-contexts.4.9
    xnetty-contexts-0.4.9.jar;D:javaEnvironment
    epoio
    eactivex
    xnetty-servo.4.9
    xnetty-servo-0.4.9.jar;D:javaEnvironment
    epocom
    etflixhystrixhystrix-core1.5.18hystrix-core-1.5.18.jar;D:javaEnvironment
    epoorghdrhistogramHdrHistogram2.1.9HdrHistogram-2.1.9.jar;D:javaEnvironment
    epojavaxinjectjavax.inject1javax.inject-1.jar;D:javaEnvironment
    epoio
    eactivex
    xnetty.4.9
    xnetty-0.4.9.jar;D:javaEnvironment
    epocom
    etflix
    ibbon
    ibbon-core2.3.0
    ibbon-core-2.3.0.jar;D:javaEnvironment
    epocommons-langcommons-lang2.6commons-lang-2.6.jar;D:javaEnvironment
    epocom
    etflix
    ibbon
    ibbon-httpclient2.3.0
    ibbon-httpclient-2.3.0.jar;D:javaEnvironment
    epocommons-collectionscommons-collections3.2.2commons-collections-3.2.2.jar;D:javaEnvironment
    epoorgapachehttpcomponentshttpclient4.5.9httpclient-4.5.9.jar;D:javaEnvironment
    epoorgapachehttpcomponentshttpcore4.4.11httpcore-4.4.11.jar;D:javaEnvironment
    epocomsunjerseyjersey-client1.19.1jersey-client-1.19.1.jar;D:javaEnvironment
    epocomsunjerseyjersey-core1.19.1jersey-core-1.19.1.jar;D:javaEnvironment
    epojavaxws
    sjsr311-api1.1.1jsr311-api-1.1.1.jar;D:javaEnvironment
    epocomsunjerseycontribsjersey-apache-client41.19.1jersey-apache-client4-1.19.1.jar;D:javaEnvironment
    epocom
    etflixservoservo-core.12.21servo-core-0.12.21.jar;D:javaEnvironment
    epocom
    etflix
    etflix-commons
    etflix-commons-util.3.0
    etflix-commons-util-0.3.0.jar;D:javaEnvironment
    epocom
    etflix
    ibbon
    ibbon-loadbalancer2.3.0
    ibbon-loadbalancer-2.3.0.jar;D:javaEnvironment
    epocom
    etflix
    etflix-commons
    etflix-statistics.1.1
    etflix-statistics-0.1.1.jar;D:javaEnvironment
    epoio
    eactivex
    xjava1.3.8
    xjava-1.3.8.jar;D:javaEnvironment
    epoorgspringframeworkootspring-boot-starter2.1.6.RELEASEspring-boot-starter-2.1.6.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworkootspring-boot2.1.6.RELEASEspring-boot-2.1.6.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworkootspring-boot-autoconfigure2.1.6.RELEASEspring-boot-autoconfigure-2.1.6.RELEASE.jar;D:javaEnvironment
    epoorgspringframeworkootspring-boot-starter-logging2.1.6.RELEASEspring-boot-starter-logging-2.1.6.RELEASE.jar;D:javaEnvironment
    epochqoslogbacklogback-classic1.2.3logback-classic-1.2.3.jar;D:javaEnvironment
    epochqoslogbacklogback-core1.2.3logback-core-1.2.3.jar;D:javaEnvironment
    epoorgapachelogginglog4jlog4j-to-slf4j2.11.2log4j-to-slf4j-2.11.2.jar;D:javaEnvironment
    epoorgapachelogginglog4jlog4j-api2.11.2log4j-api-2.11.2.jar;D:javaEnvironment
    epoorgslf4jjul-to-slf4j1.7.26jul-to-slf4j-1.7.26.jar;D:javaEnvironment
    epojavaxannotationjavax.annotation-api1.3.2javax.annotation-api-1.3.2.jar;D:javaEnvironment
    epoorgyamlsnakeyaml1.23snakeyaml-1.23.jar com.drawnblue.UserApplication
      2 2019-08-20 21:49:16.138  INFO 2896 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$39244cdd] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
      3 
      4   .   ____          _            __ _ _
      5  /\ / ___'_ __ _ _(_)_ __  __ _    
      6 ( ( )\___ | '_ | '_| | '_ / _` |    
      7  \/  ___)| |_)| | | | | || (_| |  ) ) ) )
      8   '  |____| .__|_| |_|_| |_\__, | / / / /
      9  =========|_|==============|___/=/_/_/_/
     10  :: Spring Boot ::        (v2.1.6.RELEASE)
     11 
     12 2019-08-20 21:49:17.557  INFO 2896 --- [           main] com.drawnblue.UserApplication            : No active profile set, falling back to default profiles: default
     13 2019-08-20 21:49:18.392  INFO 2896 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=f26475a6-8ec9-369b-81c6-da54b33473b9
     14 2019-08-20 21:49:18.422  INFO 2896 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$39244cdd] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
     15 2019-08-20 21:49:18.758  INFO 2896 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8002 (http)
     16 2019-08-20 21:49:18.793  INFO 2896 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
     17 2019-08-20 21:49:18.793  INFO 2896 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
     18 2019-08-20 21:49:18.974  INFO 2896 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
     19 2019-08-20 21:49:18.974  INFO 2896 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1390 ms
     20 2019-08-20 21:49:21.276  WARN 2896 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
     21 2019-08-20 21:49:21.276  INFO 2896 --- [           main] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
     22 2019-08-20 21:49:21.284  WARN 2896 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
     23 2019-08-20 21:49:21.284  INFO 2896 --- [           main] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
     24 2019-08-20 21:49:21.600  INFO 2896 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
     25 2019-08-20 21:49:22.061  INFO 2896 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService
     26 2019-08-20 21:49:22.344  INFO 2896 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8002 (http) with context path ''
     27 2019-08-20 21:49:22.430  INFO 2896 --- [           main] o.s.c.a.n.registry.NacosServiceRegistry  : nacos registry, user 192.168.179.1:8002 register finished
     28 2019-08-20 21:49:22.434  INFO 2896 --- [           main] com.drawnblue.UserApplication            : Started UserApplication in 11.304 seconds (JVM running for 13.348)
     29 2019-08-20 21:49:27.223  INFO 2896 --- [nio-8002-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
     30 2019-08-20 21:49:27.225  INFO 2896 --- [nio-8002-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
     31 2019-08-20 21:49:27.238  INFO 2896 --- [nio-8002-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 13 ms
     32 ======================[org.springframework.cloud.alibaba.nacos.NacosServiceInstance@2bcfc07f, org.springframework.cloud.alibaba.nacos.NacosServiceInstance@291f102]
     33 http://192.168.179.1:8011/userService/findById/{id}------targetUrl    org.springframework.web.client.RestTemplate@3910fe11
     34 2019-08-20 21:49:29.040  INFO 2896 --- [nio-8002-exec-1] c.netflix.config.ChainedDynamicProperty  : Flipping property: 192.168.179.1.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
     35 2019-08-20 21:49:29.096  INFO 2896 --- [nio-8002-exec-1] c.netflix.loadbalancer.BaseLoadBalancer  : Client: 192.168.179.1 instantiated a LoadBalancer: DynamicServerListLoadBalancer:{NFLoadBalancer:name=192.168.179.1,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
     36 2019-08-20 21:49:29.107  INFO 2896 --- [nio-8002-exec-1] c.n.l.DynamicServerListLoadBalancer      : Using serverListUpdater PollingServerListUpdater
     37 2019-08-20 21:49:29.120  INFO 2896 --- [nio-8002-exec-1] c.n.l.DynamicServerListLoadBalancer      : DynamicServerListLoadBalancer for client 192.168.179.1 initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=192.168.179.1,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:org.springframework.cloud.alibaba.nacos.ribbon.NacosServerList@623249f7
     38 2019-08-20 21:49:29.175 ERROR 2896 --- [nio-8002-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: No instances available for 192.168.179.1] with root cause
     39 
     40 java.lang.IllegalStateException: No instances available for 192.168.179.1
     41     at org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.execute(RibbonLoadBalancerClient.java:119) ~[spring-cloud-netflix-ribbon-2.1.2.RELEASE.jar:2.1.2.RELEASE]
     42     at org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.execute(RibbonLoadBalancerClient.java:99) ~[spring-cloud-netflix-ribbon-2.1.2.RELEASE.jar:2.1.2.RELEASE]
     43     at org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor.intercept(LoadBalancerInterceptor.java:58) ~[spring-cloud-commons-2.1.2.RELEASE.jar:2.1.2.RELEASE]
     44     at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:92) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     45     at org.springframework.http.client.InterceptingClientHttpRequest.executeInternal(InterceptingClientHttpRequest.java:76) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     46     at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     47     at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     48     at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:735) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     49     at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:670) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     50     at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:338) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     51     at com.drawnblue.usercontroller.UserController.findById2(UserController.java:41) ~[classes/:na]
     52     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161]
     53     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_161]
     54     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_161]
     55     at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_161]
     56     at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     57     at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     58     at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     59     at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     60     at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     61     at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     62     at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     63     at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     64     at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     65     at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     66     at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
     67     at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     68     at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
     69     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
     70     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
     71     at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.21.jar:9.0.21]
     72     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
     73     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
     74     at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     75     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     76     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
     77     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
     78     at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     79     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     80     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
     81     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
     82     at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     83     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     84     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
     85     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
     86     at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     87     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
     88     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
     89     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
     90     at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
     91     at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.21.jar:9.0.21]
     92     at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.21.jar:9.0.21]
     93     at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.21.jar:9.0.21]
     94     at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.21.jar:9.0.21]
     95     at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.21.jar:9.0.21]
     96     at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.21.jar:9.0.21]
     97     at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.21.jar:9.0.21]
     98     at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.21.jar:9.0.21]
     99     at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853) [tomcat-embed-core-9.0.21.jar:9.0.21]
    100     at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587) [tomcat-embed-core-9.0.21.jar:9.0.21]
    101     at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.21.jar:9.0.21]
    102     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_161]
    103     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_161]
    104     at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.21.jar:9.0.21]
    105     at java.lang.Thread.run(Thread.java:748) [na:1.8.0_161]

    主要代码如下:

    package com.drawnblue;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    import org.springframework.cloud.client.loadbalancer.LoadBalanced;
    import org.springframework.context.annotation.Bean;
    import org.springframework.web.client.RestTemplate;
    
    @SpringBootApplication
    @EnableDiscoveryClient
    public class UserApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(UserApplication.class, args);
        }
    
        @Bean
        @LoadBalanced
        public RestTemplate restTemplate() {
            return new RestTemplate();
        }
    }
    

      conotroller

     1 package com.drawnblue.usercontroller;
     2 
     3 import com.drawnblue.entity.User;
     4 import org.springframework.beans.factory.annotation.Autowired;
     5 import org.springframework.cloud.client.ServiceInstance;
     6 import org.springframework.cloud.client.discovery.DiscoveryClient;
     7 import org.springframework.http.ResponseEntity;
     8 import org.springframework.web.bind.annotation.GetMapping;
     9 import org.springframework.web.bind.annotation.PathVariable;
    10 import org.springframework.web.bind.annotation.RestController;
    11 import org.springframework.web.client.RestTemplate;
    12 
    13 import java.util.List;
    14 
    15 @RestController
    16 public class UserController {
    17     @Autowired
    18     private RestTemplate restTemplate;
    19     @Autowired
    20     private DiscoveryClient discoveryClient;
    21     @GetMapping("/test/{id}")
    22     public User findById(@PathVariable Long id) {
    23         System.out.println("調用kaishi");
    24         ResponseEntity<User> body = this.restTemplate.getForEntity("http://user-service/userService/findById/"+id, User.class);
    25         System.out.println("調用完成");
    26         return body.getBody();
    27     }
    28     @GetMapping("/getInstances")
    29     public List<ServiceInstance> getInstances(){
    30         return this.discoveryClient.getInstances("user-service");
    31     }
    32     @GetMapping("/test1/{id}")
    33     public User findById2(@PathVariable Long id){
    34         List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
    35         System.out.println("======================"+instances);
    36         String  targetURL = instances.stream()
    37                 .map(instance -> instance.getUri().toString()+"/userService/findById/{id}")
    38                 .findFirst().orElseThrow(()-> new IllegalArgumentException("当前没有实例"));
    39 
    40         System.out.println(targetURL+"------targetUrl"+"    "+this.restTemplate);
    41         ResponseEntity<User> body =  this.restTemplate.getForEntity(targetURL,User.class,1);
    42         return body.getBody();
    43     }
    44 }

    根据日志中的url和传值id=1直接在浏览器都能返回,但是调用改接口就报错:

    最终发现是因为

     @LoadBalanced
    的原因。
    加了了注解 @LoadBalanced 之后,我们的r estTemplate 会走这个类RibbonLoadBalancerClient,断点进入了如下的页面,serverid必须是我们访问的服务名称 ,当我们直接输入ip的时候获取的server是null,就会抛出异常
    当我把这个注释掉以后,重启一下,再去访问ok.
    再次访问:

     手写的随机负载均衡代码如下:

    1     @RequestMapping("/getUserT/{id}")
    2     public User getUserByRestTemplate(@PathVariable("id") String id){
    3     List<ServiceInstance> list = this.discoveryClient.getInstances("user-service");
    4     List<String> targetUrls = list.stream().map(serviceInstance -> serviceInstance.getUri().toString()).collect(Collectors.toList());
    5     int i = new Random().nextInt(targetUrls.size());
    6         System.out.println("-------"+targetUrls.get(i).toString());
    7     ResponseEntity<User> response = restTemplate.getForEntity(targetUrls.get(i)+"/test/{id}",User.class,id);
    8         return response.getBody();
    9     }

    运行日志:

    说明实现了随机,并没有轮询访问

    
    
  • 相关阅读:
    汪曾祺《生活是很好玩的》有感
    中小学Python编程语言教学
    1. python 基础课程目录
    白盒测试之gmock入门篇
    Apache与Tomcat 区别联系
    白盒测试之gtest第一个demo
    白盒测试之初识gtest工具
    纯手工打造dropdownlist控件
    android 线程的使用总结
    染色板QPlette
  • 原文地址:https://www.cnblogs.com/xiaoyao-001/p/11385921.html
Copyright © 2011-2022 走看看