欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Idea使用Grpc客户端,服务端和proto文件

程序员文章站 2022-03-26 22:57:53
...

idea装proto插件:

Idea使用Grpc客户端,服务端和proto文件

在项目main下新建proto文件夹

注意:在java包下面建proto文件,编译会找不到

Idea使用Grpc客户端,服务端和proto文件

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.12.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>


    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <grpc.version>1.27.1</grpc.version><!-- CURRENT_GRPC_VERSION -->
        <protobuf.version>3.6.1</protobuf.version>
        <protoc.version>3.6.1</protoc.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>io.grpc</groupId>
                <artifactId>grpc-bom</artifactId>
                <version>${grpc.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty-shaded</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.2</version>
            <scope>provided</scope> <!-- not needed at runtime -->
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-testing</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java-util</artifactId>
            <version>${protobuf.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>2.25.1</version>
            <scope>test</scope>
        </dependency>
<!--
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
            <version>3.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>-->
    </dependencies>


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

<!-- 打包 
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
                <configuration>
                    <!-- 指定该Main Class为全局的唯一入口 -->
                    <mainClass>com.demo.DemoApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中-->
                        </goals>
                    </execution>
                </executions>
            </plugin>-->
    </build>

</project>

proto文件:

syntax = "proto3";
option java_multiple_files = true;
option java_package = "com.example.demo.vo";

import public "google/protobuf/timestamp.proto";

message StudentVo{
    string name=1;
    string address=2;
    oneof oneof_bornDate {
        string bornDate = 12;
    }
    oneof oneof_createTime {
        string createTime = 13;
    }

}
message StdS{
    repeated StudentVo list=1;
    string name=2;
}

服务端:

service文件

syntax = "proto3";
option java_package = "com.demo.grpc.service";
option java_outer_classname = "DemoServiceProto";
service Demoervice{
    rpc test(StudentVo) returns (StudentVo);
}

实现service中的方法:

@GRpcService(interceptors = {LogInterceptor.class})
public class DemoGrpcProxy extends DemoServiceGrpc.DemoServiceImplBase {
    private static Logger logger = LoggerFactory.getLogger(DemoGrpcProxy .class);

//重写service服务的方法
}
GRpcService注解:
/**
 * 自定义注解,用于获取Spring扫描到的类
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Service
public @interface GRpcService {

    boolean applyGlobalInterceptors() default true;

    Class<? extends ServerInterceptor>[] interceptors() default {};
}

拦截器:

/***
 * Description:两种方式配置拦截器
 *    1.  @GRpcGlobalInterceptor                                  为全局拦截器
 *    2.  @GRpcService(interceptors = { LogInterceptor.class })   在需要拦截的类上加上
 *
 */

@Component
@GRpcGlobalInterceptor
public class LogInterceptor implements ServerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LogInterceptor.class);

    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
                                                                 ServerCallHandler<ReqT, RespT> next) {
        logger.info("interceptCall 方法={}",call.getMethodDescriptor().getFullMethodName());
        return next.startCall(call, headers);
    }
}

 

客户端:

获取服务: GrpcDemoClientService

@Component
public class GrpcDemoClientService {
    private DemoServiceGrpc.DemoServiceBlockingStub demoServiceBlockingStub;

    @PostConstruct
    public void init() {
        String target = "zookeeper:///" + GrpcDemoClientService .SERVICE_NAME;
        ManagedChannel channel = ManagedChannelBuilder.forTarget(target)
                .usePlaintext()
                .build();
        this.demoServiceBlockingStub= GrpcDemoClientService .newBlockingStub(channel);
    }

    public DemoServiceGrpc.DemoServiceBlockingStub demoServiceBlockingStub getDemoServiceBlockingStub () {
        return demoServiceBlockingStub ;
    }
}

调用:

@RestController
@RequestMapping("/system")
public class DemoController{
    private static final Logger logger = LoggerFactory.getLogger(DemoController.class);

    private static final String EXCEPTION_MSE_STR = "系统内部异常!";
    @Autowired
    private GrpcDemoClientService  grpcDemoClientService;

    //根据条件分页查询客户订单系统

    @RequestMapping(value = "/getDemo", method = {RequestMethod.POST})
    @CrossOrigin
    public ResponsePagerDTO getDemo() {
        // 响应DTO
        Response response = new Response;
        try {
            // 调用grpc
            Response response =grpcDemoClientService.getDemoServiceBlockingStub().getDemo();
        } catch (Exception e) {
            logger.error(EXCEPTION_MSE_STR, e);
        }
        return response;
    }
}

 

相关标签: Json