从Spring 6和Spring Boot 3开始,与OpenFeign和Retrofit等其他声明式客户端类似,Spring框架支持以Java接口的形式创建RSocket服务,并为RSocket交换提供带注释的方法。本教程将教我们使用@RSocketExchange为RSocket协议创建一个声明式请求者客户端。
声明式HTTP接口是一种Java接口,它有助于减少样板代码,生成实现该接口的代理,并在框架级别执行交换。
我们需要引入最新版本的spring-boot-starter-rsocket依赖,以包含所有必要的类和接口。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-rsocket</artifactId>
</dependency>
@RSocketExchange注解,将RSocket服务接口的方法声明为RSocket端点。它接受一个` value `参数来定义端点路由。@RSocketExchange用于HTTP传输,类似于@RequestMapping用于表示接口级别的公共路由,可以被所有服务方法继承。
public interface MessageService {
@RSocketExchange("message")
public Mono<String> sendMessage(Mono<String> requestObject);
}
服务方法可以接受以下方法参数:
public interface MessageService {
@RSocketExchange("greeting/{name}")
public Mono<String> sendMessage(@DestinationVariable("name") String name, @Payload Mono<String> greetingMono);
}
在底层,Spring生成一个实现MessageService接口的代理,并使用底层的RSocketRequester执行交换。
我们知道,Spring boot自动配置会自动配置RSocketRequester。我们的建造者。我们可以使用构建器来创建RSocketRequester。
@Autowired
RSocketRequester.Builder requesterBuilder;
//In any method
RSocketRequester rsocketRequester = requesterBuilder.tcp("localhost", 7000);
最后,我们可以使用RSocketRequester来初始化RSocketServiceProxyFactory,它最终会被用来为任何带有@RSocketExchange方法的RSocket服务接口创建客户端代理。
RSocketServiceProxyFactory factory = RSocketServiceProxyFactory.builder(rsocketRequester).build();
MessageService service = factory.createClient(MessageService.class);
最后,我们可以使用创建的服务代理来调用交换方法。让我们一起来看完整的例子。
@SpringBootApplication
@Slf4j
public class App implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@Autowired
RSocketRequester.Builder requesterBuilder;
@Override
public void run(String... args) throws Exception {
RSocketRequester rsocketRequester = requesterBuilder.tcp("localhost", 7000);
RSocketServiceProxyFactory factory = RSocketServiceProxyFactory.builder(rsocketRequester).build();
MessageService service = factory.createClient(MessageService.class);
Mono<String> response = service.sendMessage("Lokesh", Mono.just("Hello there!"));
response.subscribe(message -> log.info("RSocket response : {}", message));
}
}
控制台中的程序输出。
...[ctor-http-nio-2] c.h.a.r.controller.MessageController : Received a greeting from Lokesh : Hello there!
...[actor-tcp-nio-2] c.xqlee.app.rsocketexchange.App : RSocket response : Hello Lokesh!
在这篇简短的Spring教程中,我们学习了Spring 6引入的一个新特性,即使用@RSocketExchange注解创建一个声明式RSocket客户端。我们学习了创建和实例化服务代理,并使用它通过TCP协议连接到远程端点。
http://blog.xqlee.com/article/1118.html