基於Zookeeper執行獨立的Lagom服務

banq發表於2016-09-26
本文討論如何開發Lagom微服務,Lagom是一個整合了微服務、RESTful、CQRS、EventSoucring、Reactive程式設計等最潮概念的開發框架。介紹見:這裡

微服務是必須結合服務定位器,在開發環境,Lagom的外掛提供了out of box之外的服務定位器,在獨立部署執行時,需要使用Zookeeper作為服務定位器。

下面展示如何使用Zookeeper作為服務定位註冊器,然後打包執行一個Lagom微服務。

服務介面:

import com.lightbend.lagom.javadsl.api.Descriptor;
import com.lightbend.lagom.javadsl.api.Service;
import com.lightbend.lagom.javadsl.api.ServiceCall;
 
import static com.lightbend.lagom.javadsl.api.Service.named;
import static com.lightbend.lagom.javadsl.api.transport.Method.POST;
 
public interface HelloWorldService extends Service {
 
    ServiceCall<String, String> sayHello();
 
    @Override
    default Descriptor descriptor() {
 
        return named("helloWorld").withCalls(Service.restCall(POST, "/msg&amp", this::sayHello)).withAutoAcl(Boolean.TRUE);
    }
}
<p class="indent">


服務實現:

import com.lightbend.lagom.javadsl.api.ServiceCall;
 
import static java.util.concurrent.CompletableFuture.completedFuture;
 
public class HelloWorldServiceImpl implements HelloWorldService {
 
    @Override
    public ServiceCall<String, String> sayHello() {
        return request -> completedFuture("Hello" + request );
    }
}
<p class="indent">


以上是我們的微服務業務,下面看看整合Zookeeper:
首先,加入zookeeper的實現到lagom服務中,在本地建立lagom-zookeeper-service-locator專案,在github上已經有這個專案模板,直接下載:
git clone https://github.com/jboner/lagom-service-locator-zookeeper.git

釋出在本地:
> sbt publishLocal

一旦被髮布後,我們得增加這個專案作為服務的依賴,開啟build.sbt,加入下面一行:

 libraryDependencies in ThisBuild += "com.lightbend.lagom" % "lagom-service-locator-zookeeper_2.11" % "1.0.0-SNAPSHOT"
<p class="indent">


現在,必須啟用服務定位器,在服務配置application.conf中定義模組類,如何訪問服務定位器zookeeper例項:

lagom {
  discovery {
    zookeeper {
      server-hostname = "127.0.0.1"   # hostname or IP-address for the ZooKeeper server
      server-port     = 2181          # port for the ZooKeeper server
      uri-scheme      = "http"        # for example: http or https
      routing-policy  = "round-robin" # valid routing policies: first, random, round-robin
    }
  }
}
<p class="indent">

現在服務能和服務定位器一起工作了,但是還不能被定位,修改服務模組類保證這個服務能夠被定位:

public class HelloWorldServiceModule extends AbstractModule implements ServiceGuiceSupport {
 
    private Environment environment;
 
    @Inject
    public HelloWorldServiceModule(Environment environment, Configuration configuration) {
        this.environment = environment;
    }
 
    @Override
    protected void configure() {
 
        bindServices(serviceBinding(HelloWorldService.class, HelloWorldServiceImpl.class));
 
        if (environment.mode() == Mode.Prod()) {
 
            try {
                ZooKeeperServiceRegistry registry = new ZooKeeperServiceRegistry(
                        ZooKeeperServiceLocator.zkUri(),
                        ZooKeeperServiceLocator.zkServicesPath());
                registry.start();
 
                // create the service instance for the service discovery
                // needs to be held on to to be able to unregister the service on shutdown
                ServiceInstance<String> serviceInstance = ServiceInstance.<String>builder()
                        .name("helloWorld")
                        .id("helloWorldId")
                        .address("localhost")
                        .port(8080)
                        .uriSpec(new UriSpec("{scheme}://{serviceAddress}:{servicePort}"))
                        .build();
 
                // register the service
                registry.register(serviceInstance);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

<p class="indent">


id引數是指向微服務的標識,name是微服務名稱。
現在你的服務能夠在獨立方式下執行,下面看看如何打包並執行服務:

從sbt控制檯打包:
> project helloWorld-imp

執行下面命令:
> dist

以獨立方式啟動服務:
/helloworld/helloWorld-impl/target/universal/

生成壓縮包:helloworldimpl-[current_version].zip
其中包含所有元素。

解壓:
unzip helloworldimpl-1.0-SNAPSHOT.zip

執行bin目錄下指令碼:
./helloworldimpl-1.0-SNAPSHOT/bin/helloworldimpl

現在你的Lagom服務已經啟動。

透過zookeeper客戶端zkCli.sh訪問,透過下面命令獲得所有服務資訊:
get /lagom/services/helloWorld/helloWorldId

會得到:

{"name":"helloWorld","id":"helloWorldId","address":"localhost",
"port":8080,"sslPort":null,"payload":null,
"registrationTimeUTC":1474744298139,"serviceType":"DYNAMIC",
"uriSpec":{"parts":[{"value":"scheme","variable":true},
{"value":"://","variable":false},
{"value":"serviceAddress","variable":true},
{"value":":","variable":false},{"value":"servicePort","variable":true}]}}
<p class="indent">



Run a Lagom service standalone with Zookeeper – Co

相關文章