![](/img/trans.png)
[英]Liferay 7 - Simplest way to consume a REST webservice doesnt work
[英]What is the simplest way to consume an external REST service in Lagom?
根据Lagom文档,我们可以定义外部服务URI(如下所示),并可以从ServiceLocator获取它。
lagomUnmanagedServices in ThisBuild := Map("weather" -> "http://localhost:3333")
在Lagom中调用外部REST API的最简单方法是什么?
我考虑在Lagom中使用WsClient,但我没有选择它。 Lagom只包含WsClient for Scala,因此它提供的结果值不是java.util.concurrent.CompletionStage
而是scala.concurrent.Future
。 将其与其他Lagom API(如CompletionStage#doWithService)结合起来很麻烦 。
从lagom中消费第三方REST服务的一种方法是使用Lagom Descriptor
编写第三方的REST规范。
想象一下你的代码想要与Slack的API交互,你可以在你的app中创建一个slack-api
项目并在那里创建Slack描述符 (当然你不需要创建一个slack-impl
)。
然后,在您的fancy-impl
代码上,您将依赖于slack-api
并且在您的FancyServiceImpl
实现中,您将在构造函数中注入SlackService
。
PS:要点是scala代码,但同样的想法适用于Lagom的Java DSL。
在Lagom中,任何第三方应用程序/服务都可以作为非托管服务进行访问。 您需要在application.conf中添加它
#external-services lagom.services { 3rd-party-service-identifier = "http://3rd-party-service-url" ... }
并且还需要将第三方服务URL添加为pom中的非托管服务像这样的.xml
<plugin>
<groupId>com.lightbend.lagom</groupId>
<artifactId>lagom-maven-plugin</artifactId>
<version>${lagom.version}</version>
<configuration>
<kafkaEnabled>false</kafkaEnabled>
<cassandraEnabled>false</cassandraEnabled>
<unmanagedServices>
<3rd-party-service-identifier>${3rd-party-service-URL}</3rd-party-service-identifier>
</unmanagedServices>
</configuration>
</plugin>
这就是让你让Lagom了解第三方服务的方法,但要使用该服务,请访问以下链接。 https://www.lagomframework.com/documentation/1.4.x/java/IntegratingNonLagom.html
由于之前的答案都不包含有关如何在Java中实现它的完整信息,因此我的方法如下:
创建Lagom API模块,例如external-service-api,并在其中放置请求/响应DTO和Lagom服务,例如:
public interface ExternalService extends Service { ServiceCall<ExternalServiceRequest, ExternalServicePostResponse> somePostMethod(); ServiceCall<NotUsed, ExternalServiceGetResponse> someGetMethod(); @Override default Descriptor descriptor(){ return Service.named("external-service").withCalls( Service.pathCall("/post-endpoint", this::somePostMethod), Service.pathCall("/get-endpoint", this::someGetMethod) ).withAutoAcl(true); } }
在impl模块中向您要使用它的external-service-api添加依赖项。
在* Module.java中注册您的服务。 使用: bindClient(ExternalService.class);
现在是棘手的部分,我找到了一些教程/存储库,其中在实现模块的pom.xml中定义了非托管服务。 它对我不起作用,我不知道为什么(Lagom v.1.4.5,Scala二进制2.12)。 我必须做的是将unmanagedServices定义放在项目root pom.xml中。 请注意,unmanagedService子元素的名称应与您在描述符中定义的相同。
<plugin> <groupId>com.lightbend.lagom</groupId> <artifactId>lagom-maven-plugin</artifactId> <version>${lagom.version}</version> <configuration> <unmanagedServices> <external-service>http://api.url.com/</external-service> </unmanagedServices> </configuration> </plugin>
注入您的服务:
@Inject public SomeConstructor(ExternalService externalService){ ... }
externalService.somePostMethod().invoke(new ExternalServiceRequest(...))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.