In this article, we are going to create a login registration microservice using gRPC and Java. If you are a beginner with gRPC, then please check this article gRPC with Java. In this project, we will create two endpoints one for registering a new user and another for login. For storing the details of the user are going to MySQL.
Let’s start the Coding
Database and Table
Create a database and inside that create a table for storing the name, emailId & password of the user, if you want you can add more fields. For now, we are going with name, emailId and password.
MYSQL Query for Creating Table
mysql> create table registration(name varchar(100),emailId varchar(100),password varchar(100));
Query OK, 0 rows affected (0.28 sec)
Now create a Maven Java project and add all required dependencies for gRPC java. Check here for all dependencies for gRPC with Java.
As we know we are going to create endpoints for registration and login, let’s create a proto file and define service, endpoints and create request and response messages.
loginRegistration.proto
syntax="proto3";
package loginRegistration;
option java_multiple_files = true;
service loginAndRegistration{
rpc Register(registration) returns (response);
rpc Login(login) returns (response);
}
message registration{
string name=1;
string emailId=2;
string password=3;
}
message response{
string reply=1;
}
message login{
string emailId=1;
string password=2;
}
MySQL Database connection
Now we need to make a connection with the MySQL database for storing and retrieving data from the database, for that we are using MySQL connector dependency. Add the following dependency for MySQL connector in your pom.xml file.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
Now inside the java folder create a package named ‘db’ and inside that package create a class named ‘DBConnection’, inside this class write a method ‘mysqlConnection’ which returns Connection
DBConnection.java
package db;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnection {
public static Connection mysqlConnection(){
Connection connection = null;
try
{
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/grpcDB?"+"user=root&password=root");
}
catch (Exception e){
System.out.println(e.getMessage());
}
return connection;
}
}
Now we need to implement a service for that first we need to generate gRPC protobufs from a proto file, for that use the following mvn command
mvn clean install
Auto-generated code in Java from the proto file. if you want you can also generate these classes in other languages.
lets write our service class ‘ServiceImpl’ by extending ‘loginAndRegistrationImplBase’
import db.DBConnection;
import io.grpc.stub.StreamObserver;
import loginRegistration.login;
import loginRegistration.loginAndRegistrationGrpc;
import loginRegistration.registration;
import loginRegistration.response;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ServiceImpl extends loginAndRegistrationGrpc.loginAndRegistrationImplBase {
Connection connection = DBConnection.mysqlConnection();
@Override
public void register(registration request, StreamObserver<response> responseObserver) {
String query = "insert into registration(name,emailId,password) values(?,?,?)";
try{
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,request.getName());
preparedStatement.setString(2,request.getEmailId());
preparedStatement.setString(3,request.getPassword());
preparedStatement.execute();
System.out.println("registered");
} catch (SQLException e) {
throw new RuntimeException(e);
}
responseObserver.onNext(response.newBuilder().setReply("added sucessfully").build());
responseObserver.onCompleted();
}
@Override
public void login(login request, StreamObserver<response> responseObserver) {
Connection connection = DBConnection.mysqlConnection();
String query = "Select * from registration where emailId = ? and password = ?";
String name="";
try{
PreparedStatement statement= connection.prepareStatement(query);
statement.setString(1,request.getEmailId());
statement.setString(2,request.getPassword());
ResultSet resultSet = statement.executeQuery();
if(resultSet.next()){
name = resultSet.getString("name");
}
else{
responseObserver.onNext(response.newBuilder().setReply("invalid credintials").build());
responseObserver.onCompleted();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
responseObserver.onNext(response.newBuilder().setReply("hiii "+ name).build());
responseObserver.onCompleted();
}
}
Here we override login and register and write our logic for registering a new user and verifying email and password for login.
Let’s create Server now, we already know that we have to add a service class on the server for accessing endpoints.
Create a Server.java file and add this ServiceImpl on the server.
Server.java
import io.grpc.ServerBuilder;
import java.io.IOException;
public class Server {
public static void main(String[] args) throws IOException, InterruptedException {
int port = 8080;
io.grpc.Server server = ServerBuilder.forPort(port).addService(new ServiceImpl()).build().start();
System.out.println("server started at port: "+port );
server.awaitTermination();
}
}
Here we choose port no 8080, now let’s start the server.
Results
Let’s test the endpoints with the help of BloomRPC. First, we register a new user after that we will test the login endpoint.
Register End Point
Here we got a proper response from the server after adding a new user “added successfully”
Login End Point
Here password is wrong so we got an “invalid credentials” response from the server.
Here we got a proper response from the server because the emailId and password is correct.
That’s all for this simple login registration project with gRPC, You can do many other things like input validation more user info fields, etc.
If this article helps you in anyhow please give your feedback in the comments and share with your friends and colleagues.