在从命令行创建并运行Hello World之后,您无疑会感激Lagom框架为您所做的一切。您无需决定需要什么基础架构,然后安装并配置它。该模板消除了建立项目或构建结构的必要性。当您创建自己的服务时,Lagom会检测更改并执行热加载。Lagom让您专注于满足您的业务需求。
Hello World中的关于关注点分离、服务描述符和注册表的介绍,将帮助您开发自己的微服务:
- 服务接口
- 服务实现
服务接口
服务接口属于api项目。例如,hello服务的服务接口存在于hello-api项目中(查找HelloService.scala源文件)。 ```scala import akka.Done import akka.NotUsed import com.lightbend.lagom.scaladsl.api. import play.api.libs.json.
trait HelloService extends Service { def hello(id: String): ServiceCall[NotUsed, String]
def useGreeting(id: String): ServiceCall[GreetingMessage, Done]
final override def descriptor = { import Service. named(“hello”) .withCalls( pathCall(“/api/hello/:id”, hello ), pathCall(“/api/hello/:id”, useGreeting _) ) .withAutoAcl(true) } }
case class GreetingMessage(message: String)
object GreetingMessage { implicit val format: Format[GreetingMessage] = Json.format[GreetingMessage] }
注意:- 服务接口继承自 [**`Service`**](https://www.lagomframework.com/documentation/latest/scala/api/com/lightbend/lagom/scaladsl/api/Service.html) ,并提供了**service .descriptor**方法的实现。- **Service.descriptor**实现返回一个**`[Descriptor](https://www.lagomframework.com/documentation/latest/scala/api/com/lightbend/lagom/scaladsl/api/Descriptor.html)`**。`HelloService`描述符定义了服务名称和它提供的REST端点。对于每个端点,在服务接口中声明一个抽象方法,如`HelloService`中所示。有关更多信息,请参见服务描述符。<a name="tsWL2"></a># 服务实现在`impl`项目中,`helo-impl`提供了服务抽象方法的实现。例如,HelloServiceImpl.scala源文件包含`HelloService.hello`服务中`hello`方法的服务实现。服务实现使用[**sharded**](https://doc.akka.io/docs/akka/2.6/typed/cluster-sharding.html#introduction)、[**persistent**](https://doc.akka.io/docs/akka/2.6/typed/persistence.html#introduction)、typed actor 提供数据持久化,使用事件溯源和读写分离技术架构。```scalaimport akka.actor.typed.ActorRefimport akka.actor.typed.Behaviorimport com.lightbend.lagom.scaladsl.api.ServiceCallimport akka.cluster.sharding.typed.scaladsl.ClusterShardingimport akka.cluster.sharding.typed.scaladsl.EntityRefimport scala.concurrent.ExecutionContextimport scala.concurrent.duration._import akka.util.Timeoutimport com.lightbend.lagom.scaladsl.api.transport.BadRequestclass HelloServiceImpl(clusterSharding: ClusterSharding)(implicit ec: ExecutionContext) extends HelloService {implicit val timeout = Timeout(5.seconds)override def hello(id: String): ServiceCall[NotUsed, String] = ServiceCall { _ =>entityRef(id).ask[Greeting](replyTo => Hello(id, replyTo)).map(greeting => greeting.message)}override def useGreeting(id: String) = ServiceCall { request =>entityRef(id).ask[Confirmation](replyTo => UseGreetingMessage(request.message, replyTo)).map {case Accepted => Donecase _ => throw BadRequest("Can't upgrade the greeting message.")}}private def entityRef(id: String): EntityRef[HelloWorldCommand] =clusterSharding.entityRefFor(HelloWorldState.typeKey, id)}
