Google Cloud Firestore using Java Microservice
Table of contents
Introduction
Firestore is a scalable NOSQL cloud database built on Google Cloud infrastructure. It can create document and collections in database. In order to connect to firestore by applications, they need service accounts to connect to Google Cloud.
Service Account
Service account is a special account used by app or compute workload engine. It uses email address as unique id. It gives access to resources for which it has permissions. It has keys. To learn more about service account please visit https://cloud.google.com/iam/docs/service-account-overview .
Service account metadata will be in .json file which should be configured as environment variable in project. In IDE, it can be configured under environment variables or in shell script as export command.
GOOGLE_APPLICATION_CREDENTIALS=/Users/mridul/Documents/myProjects/fda/src/main/resources/fda-service-acc.json
Firestore Database client
Below function will give firestore db client or instance which can be used by service.
public Firestore getFirestoreService(){
//System.out.println("Env "+System.getenv("GOOGLE_APPLICATION_CREDENTIALS"));
Firestore firestoreService = null;
try{
FirestoreOptions firestoreOptions =
FirestoreOptions.getDefaultInstance().toBuilder()
.setProjectId(projectId)
.setCredentials(GoogleCredentials.getApplicationDefault())
.build();
firestoreService = firestoreOptions.getService();
}catch(Exception ex){
}
return firestoreService;
}
}
public String createOrder(Order order){
try {
FirestoreConfig config = new FirestoreConfig();
Firestore db = config.getFirestoreService();
OrderMapper orderMapper = new OrderMapper();
OrderDto orderDto = orderMapper.convertToDto(order);
DocumentReference docRef = db.collection("orders").document(UUID.randomUUID().toString());
ApiFuture<WriteResult> result = docRef.set(orderDto);
return "SUCCESS";
}catch(Exception ex){
ex.printStackTrace();
return "FAILURE";
}
}
Subscribe to my newsletter
Read articles from Mridul Deka directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Mridul Deka
Mridul Deka
I am a software developer who likes exploring new things, contribute back to community.