当前位置:   article > 正文

微服务 SpringBoot 3.0 内置声明式HTTP客户端与注册中心服务绑定_@getexchange

@getexchange

1 SpringBoot3.0 新特性

SpringBoot3.0 正式版发布后,最低支持JDK17并支持使用 GraalVM 将 Spring 的应用程序编译成本地可执行的镜像文件以及Http interface内置声明式的HTTP客户端等许多新特性。

2 声明式客户端使用

2.1 引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

2.2 创建 Http interface 类型

在接口类上添加注解 @HttpExchange 声明此类是 http interface 端点,并使用如下注解增加方法接口
@GetExchange: for HTTP GET requests.
@PostExchange: for HTTP POST requests.
@PutExchange: for HTTP PUT requests.
@DeleteExchange: for HTTP DELETE requests.
@PatchExchange: for HTTP PATCH requests.

@HttpExchange
public interface RemoteDemoApi {

    @GetExchange("/demo")
    String demo();

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2.3 注入声明式客户端

通过HttpServiceProxyFactory 携带目标接口的 BaseUrl 实现 webclient 和 http interface 的关联,使用ReactorLoadBalancerExchangeFilterFunction 负载均衡通过服务名从注册中心获取地址。

@Autowired
private ReactorLoadBalancerExchangeFilterFunction reactorLoadBalancerExchangeFilterFunction;

@Bean
public RemoteDemoApi remoteDemoLoadBalancer() {
    WebClient client = WebClient.builder().filter(reactorLoadBalancerExchangeFilterFunction).baseUrl("http://UpmsService/").build();
    HttpServiceProxyFactory factory = HttpServiceProxyFactory.builder(WebClientAdapter.forClient(client)).build();
    return factory.createClient(RemoteDemoApi.class);
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2.4 测试调用

@RestController
@RequestMapping("/test")
public class TestController {
	private final RemoteDemoApi remoteDemoApi;
	
	public TestController(RemoteDemoApi remoteDemoApi) {
	    this.remoteDemoApi = remoteDemoApi;
	}
	
	@GetMapping
	public String demo() {
	    return remoteDemoApi.demo();
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/268150
推荐阅读
相关标签
  

闽ICP备14008679号