gRPC Server Setup with Gradle

Step 1 : Add This Code into bulid.gradle and Change the version Accordingly
plugins {
id 'java'
id 'idea'
id 'com.google.protobuf' version '0.9.4'
}
group = 'org.example.com'
version = '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
protobuf {
protoc {
artifact = "com.google.protobuf:protoc:3.25.5"
}
plugins {
grpc {
artifact = 'io.grpc:protoc-gen-grpc-java:1.70.0'
}
}
generateProtoTasks {
all()*.plugins {
grpc {}
}
}
}
sourceSets.main.java.srcDir new File(buildDir, 'generated/source')
dependencies {
runtimeOnly 'io.grpc:grpc-netty-shaded:1.70.0'
implementation 'io.grpc:grpc-protobuf:1.70.0'
implementation 'io.grpc:grpc-stub:1.70.0'
compileOnly 'org.apache.tomcat:annotations-api:6.0.53' // necessary for Java 9+
testImplementation platform('org.junit:junit-bom:5.10.0')
testImplementation 'org.junit.jupiter:junit-jupiter'
}
test {
useJUnitPlatform()
}
Step 2 : Save and Build the project using gradle icon
Step 3 : Add a package to src/main package name is proto
syntax ='proto3';
package dummy;
option java_package='com.proto.dummy';
option java_multiple_files= true;
message Dummymessage{
}
service Dummyservice{}
Step 4 : Add Another package with name greeting.server in src/main/java
Step 5 : Create a java file name GreetingServer
package greeting.server;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import java.io.IOException;
public class GreetingServer {
public static void main(String[] args) throws IOException, InterruptedException {
int port =50051;
Server server = ServerBuilder.forPort(port).build();
server.start();
System.out.println("Server started");
System.out.println("listening to port"+ port);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("received shutdown request");
server.shutdown();
System.out.println("Server Stopped");
}));
server.awaitTermination();
}
}
Project Structure
Before Running the above code we need some changes
— Go to settings and find gradle the change
Build and run in to IntelliJ IDEA and change Run tests into IntelliJ IDEA
Settings
Then Go To Edit configurations add Application
Change Name : GreetingServer
Build and Run To java 17
-cp to Grpc-java.main
Add GreetingServer file in main file
Apply and Okay
Then Run the project
OUTPUT for Above program
Subscribe to my newsletter
Read articles from Raju Manoj directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
