在 Linux 上创建第一个 Java Service Fabric Reliable Actors 应用程序Create your first Java Service Fabric Reliable Actors application on Linux

借助本快速入门,只需几分钟即可在 Linux 开发环境中创建第一个 Azure Service Fabric Java 应用程序。This quick-start helps you create your first Azure Service Fabric Java application in a Linux development environment in just a few minutes. 完成后,即拥有一个在本地开发群集上运行的简单 Java 单一服务应用程序。When you are finished, you'll have a simple Java single-service application running on the local development cluster.

先决条件Prerequisites

开始之前,请安装 Service Fabric SDK、Service Fabric CLI、Yeoman,设置 Java 开发环境,并在 Linux 开发环境中设置开发群集。Before you get started, install the Service Fabric SDK, the Service Fabric CLI, Yeoman, setup the Java development environment, and setup a development cluster in your Linux development environment. 如果使用 Mac OS X,则可使用 Docker 在 Mac 上设置开发环境If you are using Mac OS X, you can Set up a development environment on Mac using Docker.

另请安装 Service Fabric CLIAlso install the Service Fabric CLI.

为 Java 安装和设置生成器Install and set up the generators for Java

Service Fabric 提供基架工具,可以借助此类工具,使用 Yeoman 模板生成器从终端创建 Service Fabric Java 应用程序。Service Fabric provides scaffolding tools which will help you create a Service Fabric Java application from terminal using Yeoman template generator. 如果尚未安装 Yeoman,请参阅 Service Fabric 入门(使用 Linux),获取有关如何设置 Yeoman 的说明。If Yeoman isn't already installed, see Service Fabric getting started with Linux for instructions on setting up Yeoman. 运行以下命令,安装用于 Java 的 Service Fabric Yeoman 模板生成器。Run the following command to install the Service Fabric Yeoman template generator for Java.

npm install -g generator-azuresfjava

基本概念Basic concepts

若要开始使用 Reliable Actors,只需了解几个基本概念:To get started with Reliable Actors, you only need to understand a few basic concepts:

  • 执行组件服务Actor service. 可以在 Service Fabric 基础结构中部署的 Reliable Services 中打包 Reliable Actors。Reliable Actors are packaged in Reliable Services that can be deployed in the Service Fabric infrastructure. 执行组件实例在命名的服务实例中激活。Actor instances are activated in a named service instance.

  • 执行组件注册Actor registration. 与 Reliable Services 一样,Reliable Actor 服务也需要注册到 Service Fabric 运行时。As with Reliable Services, a Reliable Actor service needs to be registered with the Service Fabric runtime. 此外,需要将执行组件类型注册到执行组件运行时。In addition, the actor type needs to be registered with the Actor runtime.

  • 执行组件接口Actor interface. 执行组件接口用于定义执行组件的强类型公共接口。The actor interface is used to define a strongly typed public interface of an actor. 在 Reliable Actor 模型术语中,执行组件接口用于定义执行组件可以理解并处理的消息类型。In the Reliable Actor model terminology, the actor interface defines the types of messages that the actor can understand and process. 其他执行组件或客户端应用程序使用此执行组件接口将消息“发送”(异步方式)到此执行组件。The actor interface is used by other actors and client applications to "send" (asynchronously) messages to the actor. Reliable Actors 可实现多个接口。Reliable Actors can implement multiple interfaces.

  • ActorProxy 类ActorProxy class. 客户端应用程序使用 ActorProxy 类调用通过执行组件接口公开的方法。The ActorProxy class is used by client applications to invoke the methods exposed through the actor interface. ActorProxy 类提供两个重要功能:The ActorProxy class provides two important functionalities:

    • 名称解析:能够在群集中找到执行组件(查找托管它的群集节点)。Name resolution: It is able to locate the actor in the cluster (find the node of the cluster where it is hosted).
    • 故障处理:例如,在需要将执行组件重新定位到群集中另一个节点的故障之后,它可以重试方法调用和重新解析执行组件的位置。Failure handling: It can retry method invocations and re-resolve the actor location after, for example, a failure that requires the actor to be relocated to another node in the cluster.

有必要提一下与执行组件接口有关的以下规则:The following rules that pertain to actor interfaces are worth mentioning:

  • 不能重载执行组件接口方法。Actor interface methods cannot be overloaded.
  • 执行组件接口方法不能有输出参数、引用参数或可选参数。Actor interface methods must not have out, ref, or optional parameters.
  • 不支持泛型接口。Generic interfaces are not supported.

创建应用程序Create the application

Service Fabric 应用程序包含一个或多个服务,每个服务都在提供应用程序功能时具有特定角色。A Service Fabric application contains one or more services, each with a specific role in delivering the application's functionality. 有了在上一部分安装的生成器,就可以轻松地创建第一个服务,并在以后添加更多服务。The generator you installed in the last section, makes it easy to create your first service and to add more later. 此外,还可使用适用于 Eclipse 的插件创建、生成和部署 Service Fabric Java 应用程序。You can also create, build, and deploy Service Fabric Java applications using a plugin for Eclipse. 请参阅使用 Eclipse 创建和部署第一个 Java 应用程序See Create and deploy your first Java application using Eclipse. 对于本快速入门,使用 Yeoman 创建具有单项服务的应用程序,该服务用于存储和获取获取计数器值。For this quick start, use Yeoman to create an application with a single service that stores and gets a counter value.

  1. 在终端中,键入 yo azuresfjavaIn a terminal, type yo azuresfjava.
  2. 命名应用程序。Name your application.
  3. 选择第一个服务的类型并将其命名。Choose the type of your first service and name it. 对于本教程,请选择“Reliable Actor 服务”。For this tutorial, choose a Reliable Actor Service. 有关其他服务类型的详细信息,请参阅 Service Fabric 编程模型概述For more information about the other types of services, see Service Fabric programming model overview. 适用于 Java 的 Service Fabric Yeoman 生成器Service Fabric Yeoman generator for Java

如果将应用程序命名为“HelloWorldActorApplication”,将执行组件命名为“HelloWorldActor”,则会创建以下基架:If you name the application "HelloWorldActorApplication" and the actor "HelloWorldActor", the following scaffolding is created:

HelloWorldActorApplication/
├── build.gradle
├── HelloWorldActor
│   ├── build.gradle
│   ├── settings.gradle
│   └── src
│       └── reliableactor
│           ├── HelloWorldActorHost.java
│           └── HelloWorldActorImpl.java
├── HelloWorldActorApplication
│   ├── ApplicationManifest.xml
│   └── HelloWorldActorPkg
│       ├── Code
│       │   ├── entryPoint.sh
│       │   └── _readme.txt
│       ├── Config
│       │   ├── _readme.txt
│       │   └── Settings.xml
│       ├── Data
│       │   └── _readme.txt
│       └── ServiceManifest.xml
├── HelloWorldActorInterface
│   ├── build.gradle
│   └── src
│       └── reliableactor
│           └── HelloWorldActor.java
├── HelloWorldActorTestClient
│   ├── build.gradle
│   ├── settings.gradle
│   ├── src
│   │   └── reliableactor
│   │       └── test
│   │           └── HelloWorldActorTestClient.java
│   └── testclient.sh
├── install.sh
├── settings.gradle
└── uninstall.sh

Reliable Actors 基本构建基块Reliable Actors basic building blocks

前面所述的基本概念可以转化为 Reliable Actor 服务的基本构建块。The basic concepts described earlier translate into the basic building blocks of a Reliable Actor service.

执行组件接口Actor interface

包含执行组件的接口定义。This contains the interface definition for the actor. 此接口定义执行组件实现和调用执行组件的客户端所共享的执行组件协定,因此合理的做法是在独立于执行组件实现的某个位置定义接口,并且其他多个服务或客户端应用程序可以共享接口。This interface defines the actor contract that is shared by the actor implementation and the clients calling the actor, so it typically makes sense to define it in a place that is separate from the actor implementation and can be shared by multiple other services or client applications.

HelloWorldActorInterface/src/reliableactor/HelloWorldActor.javaHelloWorldActorInterface/src/reliableactor/HelloWorldActor.java:

public interface HelloWorldActor extends Actor {
    @Readonly   
    CompletableFuture<Integer> getCountAsync();

    CompletableFuture<?> setCountAsync(int count);
}

执行组件服务Actor service

包含执行组件实现和执行组件注册代码。This contains your actor implementation and actor registration code. 执行组件类实现执行组件接口。The actor class implements the actor interface. 这是执行组件的工作位置。This is where your actor does its work.

HelloWorldActor/src/reliableactor/HelloWorldActorImplHelloWorldActor/src/reliableactor/HelloWorldActorImpl:

@ActorServiceAttribute(name = "HelloWorldActorService")
@StatePersistenceAttribute(statePersistence = StatePersistence.Persisted)
public class HelloWorldActorImpl extends FabricActor implements HelloWorldActor {
    private Logger logger = Logger.getLogger(this.getClass().getName());

    public HelloWorldActorImpl(FabricActorService actorService, ActorId actorId){
        super(actorService, actorId);
    }

    @Override
    protected CompletableFuture<?> onActivateAsync() {
        logger.log(Level.INFO, "onActivateAsync");

        return this.stateManager().tryAddStateAsync("count", 0);
    }

    @Override
    public CompletableFuture<Integer> getCountAsync() {
        logger.log(Level.INFO, "Getting current count value");
        return this.stateManager().getStateAsync("count");
    }

    @Override
    public CompletableFuture<?> setCountAsync(int count) {
        logger.log(Level.INFO, "Setting current count value {0}", count);
        return this.stateManager().addOrUpdateStateAsync("count", count, (key, value) -> count > value ? count : value);
    }
}

执行组件注册Actor registration

执行组件服务必须使用 Service Fabric 运行时中的服务类型注册。The actor service must be registered with a service type in the Service Fabric runtime. 为了使执行组件服务能够运行执行组件实例,还必须向执行组件服务注册执行组件类型。In order for the Actor Service to run your actor instances, your actor type must also be registered with the Actor Service. ActorRuntime 注册方法为执行组件执行此操作。The ActorRuntime registration method performs this work for actors.

HelloWorldActor/src/reliableactor/HelloWorldActorHostHelloWorldActor/src/reliableactor/HelloWorldActorHost:

public class HelloWorldActorHost {

private static final Logger logger = Logger.getLogger(HelloWorldActorHost.class.getName());

public static void main(String[] args) throws Exception {

        try {

            ActorRuntime.registerActorAsync(HelloWorldActorImpl.class, (context, actorType) -> new FabricActorService(context, actorType, (a,b)-> new HelloWorldActorImpl(a,b)), Duration.ofSeconds(10));
            Thread.sleep(Long.MAX_VALUE);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Exception occurred", e);
            throw e;
        }
    }
}

构建应用程序Build the application

Service Fabric Yeoman 模板包含 Gradle 的生成脚本,可用于从终端生成应用程序。The Service Fabric Yeoman templates include a build script for Gradle, which you can use to build the application from the terminal. Service Fabric Java 依赖项从 Maven 提取。Service Fabric Java dependencies get fetched from Maven. 若要生成和使用 Service Fabric Java 应用程序,需确保已安装 JDK 和 Gradle。To build and work on the Service Fabric Java applications, you need to ensure that you have JDK and Gradle installed. 如果尚未安装,请参阅 Service Fabric 入门(使用 Linux),获取有关如何安装 JDK 和 Gradle 的说明。If they are not installed, see Service Fabric getting started with Linux for instructions on installing JDK and Gradle.

若要生成并打包应用程序,请运行以下命令:To build and package the application, run the following:

cd HelloWorldActorApplication
gradle

部署应用程序Deploy the application

生成应用程序后,可以将其部署到本地群集。Once the application is built, you can deploy it to the local cluster.

  1. 连接到本地 Service Fabric 群集(该群集必须已设置且正在运行)。Connect to the local Service Fabric cluster (the cluster must be setup and running).

    sfctl cluster select --endpoint http://localhost:19080
    
  2. 运行模板中提供的安装脚本可将应用程序包复制到群集的映像存储区、注册应用程序类型和创建应用程序实例。Run the install script provided in the template to copy the application package to the cluster's image store, register the application type, and create an instance of the application.

    ./install.sh
    

部署生成的应用程序时,其方式与部署任何其他 Service Fabric 应用程序相同。Deploying the built application is the same as any other Service Fabric application. 如需详细的说明,请参阅相关文档,了解如何使用 Service Fabric CLI 管理 Service Fabric 应用程序See the documentation on managing a Service Fabric application with the Service Fabric CLI for detailed instructions.

这些命令的参数可以在应用程序包内的生成清单中找到。Parameters to these commands can be found in the generated manifests inside the application package.

应用程序部署完以后,请打开浏览器并导航到 Service Fabric Explorer,其地址为 http://localhost:19080/ExplorerOnce the application has been deployed, open a browser and navigate to Service Fabric Explorer at http://localhost:19080/Explorer. 然后,展开“应用程序”节点,注意现在有一个条目是用于应用程序类型,另一个条目用于该类型的第一个实例。Then, expand the Applications node and note that there is now an entry for your application type and another for the first instance of that type.

Important

必须将证书配置为向 Service Fabric 运行时验证应用程序,才能将应用程序部署到 Azure 中的安全 Linux 群集。 这样可便于 Reliable Actors 服务与基础 Service Fabric 运行时 API 通信。 若要了解详细信息,请参阅将 Reliable Services 应用程序配置为在 Linux 群集上运行

启动测试客户端并执行故障转移Start the test client and perform a failover

执行组件本身不执行任何操作,它们需要其他服务或客户端向其发送消息。Actors do not do anything on their own, they require another service or client to send them messages. 执行组件模板包含简单的测试脚本,可用于与执行组件服务交互。The actor template includes a simple test script that you can use to interact with the actor service.

Note

测试客户端使用 ActorProxy 类与执行组件进行通信,执行组件必须在执行组件服务所在的群集内运行或共享相同的 IP 地址空间。 可以在本地开发群集所在的计算机上运行测试客户端。 但是,若要与远程群集中的执行组件进行通信,必须在处理与执行组件的外部通信的群集上部署网关。

  1. 使用监视实用工具运行脚本,查看执行组件服务的输出。Run the script using the watch utility to see the output of the actor service. 测试脚本对角色调用 setCountAsync() 方法来递增计数器,对角色调用 getCountAsync() 方法来获取新的计数器值,并向控制台显示该值。The test script calls the setCountAsync() method on the actor to increment a counter, calls the getCountAsync() method on the actor to get the new counter value, and displays that value to the console.

    若为 MAC OS X,需要运行下面的附加命令,将 HelloWorldTestClient 文件夹复制到容器内的某位置。In case of MAC OS X, you need to copy the HelloWorldTestClient folder into the some location inside the container by running the following additional commands.

     docker cp HelloWorldTestClient [first-four-digits-of-container-ID]:/home
     docker exec -it [first-four-digits-of-container-ID] /bin/bash
     cd /home
    
    cd HelloWorldActorTestClient
    watch -n 1 ./testclient.sh
    
  2. 在 Service Fabric Explorer 中,找到托管角色服务的主要副本的节点。In Service Fabric Explorer, locate the node hosting the primary replica for the actor service. 在以下屏幕截图中,该节点是节点 3。In the screenshot below, it is node 3. 主要服务副本处理读写操作。The primary service replica handles read and write operations. 然后将服务状态更改向外复制到次要副本,该副本在下方屏幕截图的节点 0 和 1 上运行。Changes in service state are then replicated out to the secondary replicas, running on nodes 0 and 1 in the screen shot below.

    在 Service Fabric Explorer 中查找主副本

  3. 在“节点”中,单击上一步找到的节点,然后从“操作”菜单中选择“停用(重启)”。In Nodes, click the node you found in the previous step, then select Deactivate (restart) from the Actions menu. 此操作重启运行主要服务副本的节点,并强制故障转移到在其他节点上运行的其中一个次要副本。This action restarts the node running the primary service replica and forces a failover to one of the secondary replicas running on another node. 该次要副本将提升为主要副本,并在其他节点上创建另一次要副本,然后主要副本开始执行读/写操作。That secondary replica is promoted to primary, another secondary replica is created on a different node, and the primary replica begins to take read/write operations. 节点重启时,请注意来自测试客户端的输出,并注意虽然发生故障转移,但计数器仍继续递增。As the node restarts, watch the output from the test client and note that the counter continues to increment despite the failover.

删除应用程序Remove the application

使用模板中提供的卸载脚本可从群集的映像存储区删除应用程序实例、注销应用程序包并删除应用程序包。Use the uninstall script provided in the template to delete the application instance, unregister the application package, and remove the application package from the cluster's image store.

./uninstall.sh

在 Service Fabric Explorer 中,可看到应用程序和应用程序类型不再显示在“应用程序”节点中。In Service Fabric explorer you see that the application and application type no longer appear in the Applications node.

Maven 上的 Service Fabric Java 库Service Fabric Java libraries on Maven

Service Fabric Java 库已托管在 Maven 中。Service Fabric Java libraries have been hosted in Maven. 可以在项目的 pom.xmlbuild.gradle 中添加依赖项,以便使用 mavenCentral 提供的 Service Fabric Java 库。You can add the dependencies in the pom.xml or build.gradle of your projects to use Service Fabric Java libraries from mavenCentral.

执行组件Actors

针对应用程序的 Service Fabric Reliable Actor 支持。Service Fabric Reliable Actor support for your application.

<dependency>
    <groupId>com.microsoft.servicefabric</groupId>
    <artifactId>sf-actors</artifactId>
    <version>1.0.0</version>
</dependency>
repositories {
    mavenCentral()
}
dependencies {
    compile 'com.microsoft.servicefabric:sf-actors:1.0.0'
}

服务Services

针对应用程序的 Service Fabric Reliable Services 支持。Service Fabric Reliable Services support for your application.

<dependency>
    <groupId>com.microsoft.servicefabric</groupId>
    <artifactId>sf-services</artifactId>
    <version>1.0.0</version>
</dependency>
repositories {
    mavenCentral()
}
dependencies {
    compile 'com.microsoft.servicefabric:sf-services:1.0.0'
}

其他Others

传输Transport

针对 Service Fabric Java 应用程序的传输层支持。Transport layer support for Service Fabric Java application. 不需向 Reliable Actor 或 Service 应用程序显式添加此依赖项,除非在传输层编程。You do not need to explicitly add this dependency to your Reliable Actor or Service applications, unless you program at the transport layer.

<dependency>
    <groupId>com.microsoft.servicefabric</groupId>
    <artifactId>sf-transport</artifactId>
    <version>1.0.0</version>
</dependency>
repositories {
    mavenCentral()
}
dependencies {
    compile 'com.microsoft.servicefabric:sf-transport:1.0.0'
}

Fabric 支持Fabric support

针对 Service Fabric(与本机 Service Fabric 运行时通信)的系统级支持。System level support for Service Fabric, which talks to native Service Fabric runtime. 不需向 Reliable Actor 或 Service 应用程序显式添加此依赖项。You do not need to explicitly add this dependency to your Reliable Actor or Service applications. 当你包括上述其他依赖项时,会自动从 Maven 提取此依赖项。This gets fetched automatically from Maven, when you include the other dependencies above.

<dependency>
    <groupId>com.microsoft.servicefabric</groupId>
    <artifactId>sf</artifactId>
    <version>1.0.0</version>
</dependency>
repositories {
    mavenCentral()
}
dependencies {
    compile 'com.microsoft.servicefabric:sf:1.0.0'
}

后续步骤Next steps

<!--Update_Description:更新元属性,更新链接 -><!--Update_Description: update meta properties, update link ->