samedi 2 mars 2019

Deploy a fullstack app in the cloud using GCP - part 2


Step 2 : the backend

Prerequisites

  • The MongoDB database up and running (see step 1)
  • A git client (install gitbash if you are under Windows)
  • An Java IDE. May suggest IntelliJ : https://www.jetbrains.com/idea/download/ . The community edition is fine.
  • A JDK version 8. The JAVA_HOME environment pointing to the directory

Steps

Now it's time to do some code. For the backend, we will use Java and Spring Boot (could have been node.js, maybe in another article !).

This is not a Java/Mongo tutorial, so we will just use the Spring sample code as a basis, and customize it to make it work on the cloud.

To get more details, look at this tutorial : https://spring.io/guides/gs/accessing-mongodb-data-rest/

  • Clone the following repo with GIT : https://github.com/benoittouron/gcpfullstack-back.git
git clone https://github.com/benoittouron/gcpfullstack-back.git
  • If you try to launch the server locally, it will fail because you do not have a Mongo instance. Before launching the server and test it locally, edit the file called : src/main/resources/application.properties with the following content :
spring.data.mongodb.uri=mongodb://admin:PASSWORD@clusterXX
spring.data.mongodb.database=rest_tutorial
  • Replace the URI with your URI. To get it, connect to your Mongo instance https://cloud.mongodb.com/ (see the previous tutorial) 
  • Click the "Connect" button, then "Connect your application" and select driver=Java, version=3.4
The version 3.4 is important. v 3.6 URIs do not work with GCP.
  • Do not forget to change the password in the URL.
  • The parameter spring.data.mongodb.database is the name of the database created on the previous episode.
  • Now, you can build and run the server locally. 
cd gcpfullstack-back
./mvnw.cmd clean install
cd target
java -jar demo-0.0.1-SNAPSHOT.war
  • You can also use your favorite IDE.
  • To test the server, you can either use CURL as in the Spring tutorial, or Postman
  • Get postman at https://www.getpostman.com/downloads/ and install it
  • Create a new collection called RestTutorial
  • Create GET request to http://localhost:8080 and run it. You should get the links to the API.
  • To create a person, use a POST request :
  • URL = http://localhost:8080/people
  • Body =
    {  
     "firstName" : "Frodo",
     "lastName" : "Baggins" 
    }
    

  • You can verify that the datas have been saved to your online Mongo instance. 
  • Use the mongo shell as shown in the first episode and to the following commands :
use rest_tutorial
show collections => the collection "person" has been created
 db.person.find({}) => displays the persons created by your API
  • Cool, you can now fill your online database. Next step : move the backend application to the cloud !

Aucun commentaire:

Enregistrer un commentaire