idea装proto插件:
在项目main下新建proto文件夹
注意:在java包下面建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中的方法:
import com.example.demo.annotation.GRpcService;
import com.example.demo.intercet.LogInterceptor;
import com.example.demo.vo.DemoServiceGrpc;
import com.example.demo.vo.StdS;
import io.grpc.stub.StreamObserver;
@GRpcService(interceptors = {LogInterceptor.class})
public class StdsGrpc extends DemoServiceGrpc.DemoServiceImplBase {
@Override
public void demo(StdS request, StreamObserver<StdS> responseObserver) {
try {
调用服务接口
StdS test = StdS.newBuilder().setName("test").build();
responseObserver.onNext(test);
responseObserver.onCompleted();
} catch (Exception e) {
responseObserver.onNext(StdS.newBuilder().setName("error").build());
responseObserver.onCompleted();
}
}
}
/**
* 自定义注解,用于获取Spring扫描到的类
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Service
public @interface GRpcService {
boolean applyGlobalInterceptors() default true;
Class<? extends ServerInterceptor>[] interceptors() default {};
}
import com.example.demo.annotation.GRpcGlobalInterceptor;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/***
* 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);
}
}
/**
* @Description: 自定义拦截注解
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface GRpcGlobalInterceptor {
}
import com.example.demo.annotation.GRpcGlobalInterceptor;
import com.example.demo.annotation.GRpcService;
import io.grpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.stereotype.Component;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @Description: 使用spring 管理grpc服务
* @version:
*/
@Component
@Order(4)
public class GRpcServerRunner implements CommandLineRunner, DisposableBean {
private static final Logger logger = LoggerFactory.getLogger(GRpcServerRunner.class);
@Autowired
private AbstractApplicationContext applicationContext;
private Server server;
@Value("${grpc.port}")
private Integer port;
@Value("${grpc.executor.num:2}")
private Integer num;
public void run(String... args) throws Exception {
logger.info("Starting gRPC Server ...");
ServerBuilder<?> serverBuilder = ServerBuilder.forPort(port);
Collection<ServerInterceptor> globalInterceptors = (Collection) this
.getBeanNamesByTypeWithAnnotation(GRpcGlobalInterceptor.class, ServerInterceptor.class).map((name) -> {
return (ServerInterceptor) this.applicationContext.getBeanFactory()
.getBean(name, ServerInterceptor.class);
}).collect(Collectors.toList());
// find and register all GRpcService-enabled beans
this.getBeanNamesByTypeWithAnnotation(GRpcService.class, BindableService.class).forEach((name) -> {
BindableService srv = (BindableService) this.applicationContext.getBeanFactory()
.getBean(name, BindableService.class);
ServerServiceDefinition serviceDefinition = srv.bindService();
GRpcService gRpcServiceAnn = (GRpcService) this.applicationContext
.findAnnotationOnBean(name, GRpcService.class);
serviceDefinition = this.bindInterceptors(serviceDefinition, gRpcServiceAnn, globalInterceptors);
serverBuilder.executor(Executors.newFixedThreadPool(num));
serverBuilder.addService(serviceDefinition);
String serviceName = serviceDefinition.getServiceDescriptor().getName();
logger.info("'{}' service has been registered.", srv.getClass().getName());
});
server = serverBuilder.build().start();
this.applicationContext.publishEvent(this.server);
logger.info("gRPC Server started, listening on port {}.", this.server.getPort());
this.startDaemonAwaitThread();
}
private ServerServiceDefinition bindInterceptors(ServerServiceDefinition serviceDefinition, GRpcService gRpcService,
Collection<ServerInterceptor> globalInterceptors) {
Stream<? extends ServerInterceptor> privateInterceptors = Stream.of(gRpcService.interceptors())
.map((interceptorClass) -> {
try {
return 0 < this.applicationContext.getBeanNamesForType(interceptorClass).length
? (ServerInterceptor) this.applicationContext.getBean(interceptorClass)
: (ServerInterceptor) interceptorClass.newInstance();
} catch (Exception var3) {
throw new BeanCreationException("Failed to create interceptor instance.", var3);
}
});
List<ServerInterceptor> interceptors = (List) Stream
.concat(gRpcService.applyGlobalInterceptors() ? globalInterceptors.stream() : Stream.empty(),
privateInterceptors).distinct().sorted(this.serverInterceptorOrderComparator())
.collect(Collectors.toList());
return ServerInterceptors.intercept(serviceDefinition, interceptors);
}
private Comparator<Object> serverInterceptorOrderComparator() {
Function<Object, Boolean> isOrderAnnotated = (obj) -> {
Order ann = obj instanceof Method ? (Order) AnnotationUtils.findAnnotation((Method) obj, Order.class)
: (Order) AnnotationUtils.findAnnotation(obj.getClass(), Order.class);
return ann != null;
};
return AnnotationAwareOrderComparator.INSTANCE.thenComparing((o1, o2) -> {
boolean p1 = (Boolean) isOrderAnnotated.apply(o1);
boolean p2 = (Boolean) isOrderAnnotated.apply(o2);
return p1 && !p2 ? -1 : (p2 && !p1 ? 1 : 0);
}).reversed();
}
private void startDaemonAwaitThread() {
Thread awaitThread = new Thread(() -> {
try {
this.server.awaitTermination();
} catch (InterruptedException var2) {
logger.error("gRPC server stopped.", var2);
Thread.currentThread().interrupt();
}
});
awaitThread.setDaemon(false);
awaitThread.start();
}
public void destroy() throws Exception {
logger.info("Shutting down gRPC server ...");
Optional.ofNullable(this.server).ifPresent(Server::shutdown);
logger.info("gRPC server stopped.");
}
private <T> Stream<String> getBeanNamesByTypeWithAnnotation(Class<? extends Annotation> annotationType,
Class<T> beanType) throws Exception {
return Stream.of(this.applicationContext.getBeanNamesForType(beanType)).filter(name -> {
BeanDefinition beanDefinition = this.applicationContext.getBeanFactory().getBeanDefinition(name);
Map<String, Object> beansWithAnnotation = this.applicationContext.getBeansWithAnnotation(annotationType);
if (beansWithAnnotation.containsKey(name)) {
return true;
} else {
return beanDefinition.getSource() instanceof AnnotatedTypeMetadata
? ((AnnotatedTypeMetadata) AnnotatedTypeMetadata.class.cast(beanDefinition.getSource()))
.isAnnotated(annotationType.getName()) : false;
}
});
}
}
客户端
import com.example.demo.vo.DemoServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class GrpcDemoClientService {
private DemoServiceGrpc.DemoServiceBlockingStub demoServiceBlockingStub;
@PostConstruct
public void init() {
String target = "zookeeper:///" + DemoServiceGrpc.SERVICE_NAME;
ManagedChannel channel = //ManagedChannelBuilder.forAddress("127.0.0.1",8086)
ManagedChannelBuilder.forTarget(target)
.usePlaintext()
.build();
this.demoServiceBlockingStub = DemoServiceGrpc.newBlockingStub(channel);
}
public DemoServiceGrpc.DemoServiceBlockingStub getDemoServiceBlockingStub() {
return demoServiceBlockingStub;
}
}
import com.example.demo.client.GrpcDemoClientService;
import com.example.demo.vo.StdS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
@Autowired
private GrpcDemoClientService grpcDemoClientService;
@RequestMapping(value = "/demo", method = {RequestMethod.GET})
public StdS getCoSeatBySearchVal() {
// 响应DTO
try {
StdS grpc = StdS.newBuilder().setName("grpc").build();
// 调用grpc
StdS demo = grpcDemoClientService.getDemoServiceBlockingStub().demo(grpc);
return demo;
} catch (Exception e) {
}
return null;
}
}