Lagom是一个集成ES/CQRS的Reactive微服务框架

Lagom是一个集成了微服务、RESTful、CQRS、EventSoucring、Reactive编程等最潮概念的开发框架。

2014年预测:为什么REST 微服务和异步 编程是一种趋势?,如今变成了现实。

Lagom缺省都是是异步的,所有的异步都是基于 Akka Stream(scala)和JDK8 CompletionStage API 实现的。

提供以下主要功能:
1.服务API
服务API 提供一种申明和实现服务接口的方法,这个服务可以被客户端直接消费调用,客户端通过服务定位器发现它所要访问的服务。这个服务API提供服务之间调用异步的Stream方式 ,同时也支持传统的同步请求-响应方式调用。

2.持久API
提供事件溯源event-sourced实体持久化,支持CQRS. Lagom跨集群节点管理持久实体的分布,激活分区sharding和水平扩展. Cassandra以out-of-the-box作为数据库.

3.开发环境
开发环境能够运行你的服务,支持Lagom底层基础设施,使用一个命令,能在代码改变时热加载你的服务,没有琐碎的脚本来设置和管理你的开发环境,代之以Lagom, 一个开发者能够很快和其他开发者合作,开发新的服务或加入现有的开发团队。

4.产品环境
Lightbend ConductR是以out-of-the-box支持生产环境,支持简单部署 监视和扩展规模。

以hellowworld为案例:
HelloService的接口代码如下:


public interface HelloService extends Service {
@Override
default Descriptor descriptor() {
return named("helloservice").with(
restCall(Method.GET,
"/api/hello/:id", hello())
).withAutoAcl(true);
}

ServiceCall<String, NotUsed, String> hello();
}

你的服务接口代码必须继承框架的Service,并提供Servicedescriptor方法实现. Service#descriptor必须返回Descriptor对象,这个对象定义了 服务名称和服务对外的REST端点。 这里是定义了REST API的调用URL,这样你就可以 http://localhost:9000/api/hello/World访问这个HelloService微服务了。

然后编写你的HellpService接口的具体实现子类:


public class HelloServiceImpl implements HelloService {

private final PersistentEntityRegistry persistentEntityRegistry;

@Inject
public HelloServiceImpl(PersistentEntityRegistry persistentEntityRegistry) {
this.persistentEntityRegistry = persistentEntityRegistry;
persistentEntityRegistry.register(HelloWorld.class);
}

@Override
public ServiceCall<String, NotUsed, String> hello() {
return (id, request) -> {
// Look up the hello world entity for the given ID.
PersistentEntityRef<HelloCommand> ref = persistentEntityRegistry.refFor(HelloWorld.class, id);
// Ask the entity the Hello command.
return ref.ask(new Hello(id, Optional.empty()));
};
}
}

这段代码内容主要是访问持久层,实现实体的查询操作,首先在HelloServiceImpl注册了PersistentEntityRegistry ,然后向PersistentEntityRegistry 注册了HelloWorld.class这个实体对象,在查询方法ServiceCall中,根据ID向PersistentEntityRegistry发出查询命令。

这里的 PersistentEntityRegistry是框架自身提供以Event Sourcing 和 CQRS方式访问数据库中的数据实体。

最后一步运行该代码:


$ cd my-first-system
$ activator
... (booting up)
> runAll
[info] Starting embedded Cassandra server
..........
[info] Cassandra server running at 127.0.0.1:4000
[info] Service locator is running at http://localhost:8000
[info] Service gateway is running at http:
//localhost:9000
[info] Service helloworld-impl listening for HTTP on 0:0:0:0:0:0:0:0:24266
[info] Service hellostream-impl listening for HTTP on 0:0:0:0:0:0:0:0:26230
(Services started, use Ctrl+D to stop and go back to the console...)

测试访问:curl http://localhost:9000/api/hello/World

项目地址:
Lightbend Lagom - Reactive Microservices | @lightb

[该贴被banq于2016-03-11 11:33修改过]