grpc etcd服務註冊發現

1、新建maven工程

pom.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.chen</groupId>
    <artifactId>grpc</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>grpc</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty</artifactId>
            <version>1.12.0</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
            <version>1.12.0</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>1.12.0</version>
        </dependency>
    </dependencies>

    <build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.5.0.Final</version>
            </extension>
        </extensions>
        <plugins>
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.5.1</version>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:3.5.1-1:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.12.0:exe:${os.detected.classifier}</pluginArtifact>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

2、protobuf生java代碼

先protobuf:compile,然後protobuf:compile-custom

compile成功後生成文件結構大致如下

3、服務方代碼

public class ApiserverImpl extends ApiServerGrpc.ApiServerImplBase {
    private static final Logger LOGGER = LoggerFactory.getLogger(ApiserverImpl.class);

    @Override
    public void addJob(Apiserver.JobRequest request, StreamObserver<Apiserver.APIResponse> responseObserver) {
        System.out.println("Step 1 創建任務");
        Apiserver.APIResponse response = Apiserver.APIResponse.newBuilder()
                .setRequestID("")
                .setSuccess(true).setMessage("").build();
        // 響應
        responseObserver.onNext(response);
        // 結束
        responseObserver.onCompleted();
    }
}

4、消費方代碼


public class ApiserverConsumerService extends AbstractConsumer<ApiServerGrpc.ApiServerBlockingStub> {

    private static final Logger LOGGER = LoggerFactory
            .getLogger(ApiserverConsumerService.class);

    public ApiserverConsumerService(String serverAppName) {
        super(serverAppName);
    }

    @GrpcCallMethodAnnotation
    public Boolean addJob(String msg) {
        System.out.println("----------api server----------");
//        HashMap<String, String> param = JSON.parseObject(msg, HashMap.class);
//        System.out.println("uuid = " + param.get("uuid"));

        Apiserver.Job job = Apiserver.Job.newBuilder().setUuid("kk001").setType(2).build();

        Apiserver.JobRequest jobRequest = Apiserver.JobRequest.newBuilder().setJob(job).build();
        ApiServerGrpc.ApiServerBlockingStub stub = getStub();
        Apiserver.APIResponse response = stub.withDeadlineAfter(1000, TimeUnit.MILLISECONDS).addJob(jobRequest);
        System.out.println("----------add job response = " + response.toString() + "----------");
        return true;
    }

    @Override
    public ApiServerGrpc.ApiServerBlockingStub initStub(Channel channel) {
        ApiServerGrpc.ApiServerBlockingStub stub = ApiServerGrpc.newBlockingStub(channel);
        return stub;
    }

    @Override
    public ServiceDescriptor getServiceDescriptor() {
        return ApiServerGrpc.getServiceDescriptor();
    }
}

5、測試代碼

public class TestAddJob {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestAddJob.class);

    public TestAddJob() {}

    public static void main(String[] args) {
        GrpcManager.setAppName("sigmax");
//        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//        ConsumerConfig consumerConfig = (ConsumerConfig)ac.getBean("consumerConfig");
//        BaseRegister register = new EtcdRegister("TestConsumer", "http://10.0.200.86:2379");
//        consumerConfig.setRegister(register);

        ConsumerConfig consumerConfig = new ConsumerConfig();
        BaseRegister register = new EtcdRegister("sigmax", "http://10.0.200.86:2379"); // dev
//        BaseRegister register = new EtcdRegister("sigmax", "http://10.0.228.114:2379"); // nx

        consumerConfig.setRegister(register);
        GrpcManager.setConsumerConfig(consumerConfig);

        ApiserverConsumerService service = new ApiserverConsumerService("sigmax");
        ConsumerServer consumerServer = new ConsumerServer(Lists.newArrayList(new AbstractConsumer[]{service}));

        try {
            consumerServer.init();
        } catch (Exception var6) {
        }

        Boolean result = service.addJob("test consumer");

    }
}

6、打包與發佈

pom.xml 增加

<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
        <!--這部分可有可無,加上的話則直接生成可運行jar包-->
        <archive>
        <manifest>
        <mainClass>com.chen.sigmax.test.TestAddJob</mainClass>
        </manifest>
        </archive>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
    </configuration>
</plugin>

然後執行項目根目錄下執行 mvn assembly:assembly,生成帶依賴庫的包target/sigmaxtest-1.0-SNAPSHOT-jar-with-dependencies.jar 。

linux只要佈署java、maven環境,本地庫~/.m2/repository正確,java -jar sigmaxtest-1.0-SNAPSHOT-jar-with-dependencies.jar即可執行<mainClass>指定的main方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章