searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

手把手教你把gRPC集成到SpringBoot3框架中

2023-08-15 08:52:07
589
0

1.使用JDK17创建工程

2.引入maven依赖

<?xml version="1.0" encoding="UTF-8"?>
<project>
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.8</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>Springboot3WithgRPCDemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Springboot3WithgRPCDemo</name>
    <description>Springboot3WithgRPCDemo</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <!-- grpc-->
        <dependency>
            <groupId>net.devh</groupId>
            <artifactId>grpc-server-spring-boot-starter</artifactId>
            <version>2.14.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>1.42.1</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
            <version>1.42.1</version>
        </dependency>
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- grpc end-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.7.0</version>
            </extension>
        </extensions>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <configuration>
                    <protocArtifact>
                        com.google.protobuf:protoc:3.6.1:exe:${os.detected.classifier}
                    </protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>
                        io.grpc:protoc-gen-grpc-java:1.22.1:exe:${os.detected.classifier}
                    </pluginArtifact>
                    <protoSourceRoot>
                        ${basedir}/src/main/proto/
                    </protoSourceRoot>
                    <outputDirectory>${basedir}/src/test/java/</outputDirectory>
                    <clearOutputDirectory>false</clearOutputDirectory>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

3.编写grpc proto文件

// demo.proto
syntax = "proto3";

option java_multiple_files = false;
option java_package = "com.example.springboot3withgrpcdemo";

message DemoRequest{
  string reqV = 1;
}
message DemoResponse {
  string rspV = 1;
}

service DemoService {
  rpc getDemo(DemoRequest) returns (DemoResponse) {};
}

4.编译proto文件生成java接口

双击以下插件生成代码

5.实现服务端grpc接口逻辑

package com.example.springboot3withgrpcdemo.grpc.impl;

import com.example.springboot3withgrpcdemo.grpc.Demo;
import com.example.springboot3withgrpcdemo.grpc.DemoServiceGrpc;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;

@GrpcService
public class DemoService extends DemoServiceGrpc.DemoServiceImplBase {

    @Override
    public void getDemo(Demo.DemoRequest req, StreamObserver<Demo.DemoResponse> rsp) {
        System.out.println("recv msg: " + req);
        String reqV = req.getReqV();
        Demo.DemoResponse replyMsg = Demo.DemoResponse.newBuilder().setRspV(reqV).build();
        rsp.onNext(replyMsg);
        rsp.onCompleted();
        System.out.println("reply msg: " + replyMsg);
    }
}

6.实现客户端grpc接口逻辑

package com.example.springboot3withgrpcdemo;

import com.example.springboot3withgrpcdemo.grpc.Demo;
import com.example.springboot3withgrpcdemo.grpc.DemoServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

public class ClientTest {
    public static void main(String[] args) {
        ManagedChannel managedChannel = ManagedChannelBuilder
                .forAddress("127.0.0.1", 9090)
                .usePlaintext()
                .build();

        DemoServiceGrpc.DemoServiceBlockingStub stub = DemoServiceGrpc.newBlockingStub(managedChannel);
        Demo.DemoRequest reqMsg = Demo.DemoRequest.newBuilder().setReqV("content at ts-" + System.currentTimeMillis()).build();
        System.out.println("send reqMsg: " + reqMsg);
        Demo.DemoResponse rspMsg = stub.getDemo(reqMsg);
        System.out.println("get rspMsg: " + rspMsg);
        managedChannel.shutdown();
    }
}

7.关键步骤:修改服务端入口类

增加@ImportAutoConfiguration内容,让SpringBoot3识别启动gRPC服务器

package com.example.springboot3withgrpcdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@ImportAutoConfiguration({
        net.devh.boot.grpc.common.autoconfigure.GrpcCommonCodecAutoConfiguration.class,
        net.devh.boot.grpc.common.autoconfigure.GrpcCommonTraceAutoConfiguration.class,
        net.devh.boot.grpc.server.autoconfigure.GrpcMetadataConsulConfiguration.class,
        net.devh.boot.grpc.server.autoconfigure.GrpcMetadataEurekaConfiguration.class,
        net.devh.boot.grpc.server.autoconfigure.GrpcMetadataNacosConfiguration.class,
        net.devh.boot.grpc.server.autoconfigure.GrpcServerAutoConfiguration.class,
        net.devh.boot.grpc.server.autoconfigure.GrpcServerFactoryAutoConfiguration.class,
        net.devh.boot.grpc.server.autoconfigure.GrpcServerMetricAutoConfiguration.class,
        net.devh.boot.grpc.server.autoconfigure.GrpcServerSecurityAutoConfiguration.class,
        net.devh.boot.grpc.server.autoconfigure.GrpcServerTraceAutoConfiguration.class
})
public class Springboot3WithgRpcDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot3WithgRpcDemoApplication.class, args);
    }

}

8.运行服务端

在9090端口提供gRPC服务

9.运行客户端

10.观察结果

客户端结果

服务端结果

结果符合预期

0条评论
作者已关闭评论
hzy
3文章数
0粉丝数
hzy
3 文章 | 0 粉丝
hzy
3文章数
0粉丝数
hzy
3 文章 | 0 粉丝
原创

手把手教你把gRPC集成到SpringBoot3框架中

2023-08-15 08:52:07
589
0

1.使用JDK17创建工程

2.引入maven依赖

<?xml version="1.0" encoding="UTF-8"?>
<project>
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.8</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>Springboot3WithgRPCDemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Springboot3WithgRPCDemo</name>
    <description>Springboot3WithgRPCDemo</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <!-- grpc-->
        <dependency>
            <groupId>net.devh</groupId>
            <artifactId>grpc-server-spring-boot-starter</artifactId>
            <version>2.14.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>1.42.1</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
            <version>1.42.1</version>
        </dependency>
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- grpc end-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.7.0</version>
            </extension>
        </extensions>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <configuration>
                    <protocArtifact>
                        com.google.protobuf:protoc:3.6.1:exe:${os.detected.classifier}
                    </protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>
                        io.grpc:protoc-gen-grpc-java:1.22.1:exe:${os.detected.classifier}
                    </pluginArtifact>
                    <protoSourceRoot>
                        ${basedir}/src/main/proto/
                    </protoSourceRoot>
                    <outputDirectory>${basedir}/src/test/java/</outputDirectory>
                    <clearOutputDirectory>false</clearOutputDirectory>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

3.编写grpc proto文件

// demo.proto
syntax = "proto3";

option java_multiple_files = false;
option java_package = "com.example.springboot3withgrpcdemo";

message DemoRequest{
  string reqV = 1;
}
message DemoResponse {
  string rspV = 1;
}

service DemoService {
  rpc getDemo(DemoRequest) returns (DemoResponse) {};
}

4.编译proto文件生成java接口

双击以下插件生成代码

5.实现服务端grpc接口逻辑

package com.example.springboot3withgrpcdemo.grpc.impl;

import com.example.springboot3withgrpcdemo.grpc.Demo;
import com.example.springboot3withgrpcdemo.grpc.DemoServiceGrpc;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;

@GrpcService
public class DemoService extends DemoServiceGrpc.DemoServiceImplBase {

    @Override
    public void getDemo(Demo.DemoRequest req, StreamObserver<Demo.DemoResponse> rsp) {
        System.out.println("recv msg: " + req);
        String reqV = req.getReqV();
        Demo.DemoResponse replyMsg = Demo.DemoResponse.newBuilder().setRspV(reqV).build();
        rsp.onNext(replyMsg);
        rsp.onCompleted();
        System.out.println("reply msg: " + replyMsg);
    }
}

6.实现客户端grpc接口逻辑

package com.example.springboot3withgrpcdemo;

import com.example.springboot3withgrpcdemo.grpc.Demo;
import com.example.springboot3withgrpcdemo.grpc.DemoServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

public class ClientTest {
    public static void main(String[] args) {
        ManagedChannel managedChannel = ManagedChannelBuilder
                .forAddress("127.0.0.1", 9090)
                .usePlaintext()
                .build();

        DemoServiceGrpc.DemoServiceBlockingStub stub = DemoServiceGrpc.newBlockingStub(managedChannel);
        Demo.DemoRequest reqMsg = Demo.DemoRequest.newBuilder().setReqV("content at ts-" + System.currentTimeMillis()).build();
        System.out.println("send reqMsg: " + reqMsg);
        Demo.DemoResponse rspMsg = stub.getDemo(reqMsg);
        System.out.println("get rspMsg: " + rspMsg);
        managedChannel.shutdown();
    }
}

7.关键步骤:修改服务端入口类

增加@ImportAutoConfiguration内容,让SpringBoot3识别启动gRPC服务器

package com.example.springboot3withgrpcdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@ImportAutoConfiguration({
        net.devh.boot.grpc.common.autoconfigure.GrpcCommonCodecAutoConfiguration.class,
        net.devh.boot.grpc.common.autoconfigure.GrpcCommonTraceAutoConfiguration.class,
        net.devh.boot.grpc.server.autoconfigure.GrpcMetadataConsulConfiguration.class,
        net.devh.boot.grpc.server.autoconfigure.GrpcMetadataEurekaConfiguration.class,
        net.devh.boot.grpc.server.autoconfigure.GrpcMetadataNacosConfiguration.class,
        net.devh.boot.grpc.server.autoconfigure.GrpcServerAutoConfiguration.class,
        net.devh.boot.grpc.server.autoconfigure.GrpcServerFactoryAutoConfiguration.class,
        net.devh.boot.grpc.server.autoconfigure.GrpcServerMetricAutoConfiguration.class,
        net.devh.boot.grpc.server.autoconfigure.GrpcServerSecurityAutoConfiguration.class,
        net.devh.boot.grpc.server.autoconfigure.GrpcServerTraceAutoConfiguration.class
})
public class Springboot3WithgRpcDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot3WithgRpcDemoApplication.class, args);
    }

}

8.运行服务端

在9090端口提供gRPC服务

9.运行客户端

10.观察结果

客户端结果

服务端结果

结果符合预期

文章来自个人专栏
开发经验
1 文章 | 1 订阅
0条评论
作者已关闭评论
作者已关闭评论
0
0