开发者社区> 问答> 正文

Spring WebClient获取请求返回“连接被拒绝:localhost /”

当我尝试通过WebClient发送GET请求时,发生了错误io.netty.channel.AbstractChannel $ AnnotatedConnectException的响应:连接被拒绝:localhost /

  • WebClient初始化*
//hostname = "localhost/127.0.0.1:8081"
//contextPath = "user-service"

    @Bean
    public WebClient userWebclient(@Value("${service.user.hostname}") final String hostname,
                                  @Value("${service.user.contextPath}") final String contextPath) {
        return WebClient
                .builder()
                .baseUrl(hostname + contextPath)
                .build();
    }

控制器

private final WebClient userWebclient;

  @GetMapping(value = "/user/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
  public Mono<String> getUserById(@NotNull @PathVariable String userId) {
      userWebclient.

      return userWebclient.get()
             .uri("/UserMock/user/" + userId)
             .header("Accept", "application/json")
             .header("Authorization", "Bearer =........")
             .exchange()
             .flatMap(response -> response.bodyToMono(String.class));
  }

错误信息

io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: localhost/127.0.0.1:8081
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
    at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:327)
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:340)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:665)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:612)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:529)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:491)
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:905)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connection refused
    ... 10 common frames omitted

展开
收起
几许相思几点泪 2019-12-26 19:52:46 2162 0
1 条回答
写回答
取消 提交回答
  • 在主机中使用

    hostname = "localhost:8081"
    

    要么

    hostname = "127.0.0.1:8081"
    
    

    代替

    hostname = "localhost/127.0.0.1:8081"
    
    2019-12-26 19:53:11
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
云栖社区特邀专家徐雷Java Spring Boot开发实战系列课程(第20讲):经典面试题与阿里等名企内部招聘求职面试技巧 立即下载
微服务架构模式与原理Spring Cloud开发实战 立即下载
阿里特邀专家徐雷Java Spring Boot开发实战系列课程(第18讲):制作Java Docker镜像与推送到DockerHub和阿里云Docker仓库 立即下载

相关实验场景

更多