Learn Spring Cloud lesson three (service providers and service consumers)

Source: Internet
Author: User
Tags mysql database nginx load balancing

First, the concept

What are service providers and service consumers.

Service provider: Refers to the callee of a service (that is, a service that serves other services)

Service consumer: Refers to the service's callers (that is, services that depend on other services)

II. Preparation of service providers

First, we need to access Http://start.spring.io, as shown in the following illustration

Next, select the version of Spring boot, the latest spring boot version is 1.5.1, as shown in the following figure.

Next, enter the following figure as shown in the group and artifact two columns.

Then we need to select some dependencies, enter "Web" in the search box, will automatically display a drop-down list about the Web, we select the first, as shown in the figure below.

After selecting the Web, you will see the web that we depend on below, as shown in the following illustration

Next, select JPA, Mysql, and finally click on the "Generate Project" button below, as shown in the following figure.

Click "Generrate Project" in the image above to pop up the dialog shown below, we click Save as saved to local.

Next, we open the development tools Intellijidea tool, and if it is the first time using the Idea tool, the interface shown in the figure below will appear, we click "Import Project".

Will pop up the interface shown in the image below, we select the Pom.xml file under the Microservice-simple-provider-user project we just generated, then click "OK"

After clicking on the "OK" in the image above, we can see the interface shown in the image below, we do nothing, just click "Next"

After clicking on the "Next" in the image above, we will see the interface shown below, and we'll just click "Next"

After clicking on the "Next" above, we can see the following interface, as we said earlier, we develop microservices using jdk1.8, so choose jdk1.8 here and click "Next"

After clicking on the "Next" in the image above, we can see the interface shown below, and we will click "Finish" directly.

After clicking "Finish", loading maven dependencies, the interface shown in the following figure will appear.

The static and templates two folders in the resources directory above are useless, we delete it, then we create a new Schema.sql file under the Resources directory, the new Schema.sql file needs to be configured " Configure data Source "," Change dialect to ... ", we first click on" Configure data source ".

After clicking on "Configure data source" above, we can see the interface shown below, we choose "MySQL" on the left, "Driver files" on the right, there is no content, we click "Download" to download the driver file.

After downloading the driver file, as shown in the image below, we click "OK"

If you have never added MySQL to your idea tool, then the Schema.sql file still prompts you to configure Data source and dialect, so how do we add mysql? We found out that, on the right side of the idea tool, there is a column of toolbars that we click in the database column.


Click on the "Database" column above we can see the image below the interface, you can see that I have not added any database, below we click on the "+" sign icon.


After clicking on the "+" icon in the image above, we see the interface shown below, we click on MySQL


Click on the "MySQL" above, we can see the image below the interface, we create a new database: "Microservice", user and password is our locally installed MySQL username and password. After that we need to test if the connection is successful (don't click Test Connection).


Before testing the connection, we need to create a new database named "Microservice", which is the same as the one we entered in the figure above, as shown in the following figure.


Now we can test whether the connection can be successful, we click on the "Test Connection", if successful, will be shown below, we click "OK"


Below we click "Apply", "OK", as shown in the figure below


After clicking on the "Apply" and "OK" above, we can see the interface shown in the figure below, we can try a SQL statement to see if we can query the results, for example, we query all the databases, we can see the results of the correct query.


After we have added the MySQL database, we have just added the Schema.sql file hint to reduce the content of one, leaving only let us configure the dialect, as shown in the figure below. We click on "Change dialect ..."


We can see the interface shown in the figure below, we can see that by default SQL dialect is Generic, since we use the database is MySQL, then we will click "Generic", in the dropdown box select "MySQL".


After selecting the dialect, the following illustration shows. We click "OK"


After clicking on the "OK" in the image above, we can see that our Schema.sql file has finally stopped reporting the exception prompt, and we have written the statement in the SQL file, as shown in the following figure.


Similarly, we create a new Data.sql file and write the INSERT statement in the file, as shown in the following figure.


Here we create a new entity class user, the directory structure as shown in the figure (Intellijidea generate Get, set method shortcut key is Alt+insert), it should be noted that because we use MySQL here, So the @generatedvalue strategy uses MySQL's primary key generation strategy, and different database primary key generation strategies are different.


Then we create an interface class Userrepository (that is, we are familiar with DAO), as shown in the figure below, the reason why let Userrepository inherit jparepository is to directly use the Jparepository interface method, Instead of having to write the interface yourself.


Next we write a controller, named Usercontroller, as shown in the following figure.


Below we have renamed the application.properties file suffix in the resources directory to. Yml, because the. yml file has powerful hints and is a fixed and concise format that is especially useful for editing configuration content. As shown in the figure below


The contents of the configuration in the Application.yml file are as follows, the following is the meaning of the configuration, first port:7900 means the access port, GENERATE-DDL: False indicates that the Sping startup does not automatically generate additions and deletions to the interface (because we will write and delete and change the interface), show-sql:true indicates that the SQL statement will be output in the console, Hibernate.ddl-auto: None means that hibernate loading does not automatically generate additions and deletions to the interface. Datasource.platform:mysql indicates that the database used is MySQL, ( Note: Datasource.url, Datasource.username, Datasource.password, Datasource.driver-class-name These four configuration is in the case of non-H2 database must be configured, we use MySQL, so the configuration is also the MySQL database information, if you are using a different database corresponding to make adjustments. In addition, because the query database may be garbled, so we added after the driver jdbc:mysql://localhost:3306/microservice "? Useunicode=true&characterencoding=utf-8"This sentence encoding configuration ) Datasource.schema:classpath: Schema.sql represents the SQL file that specifies the build table, and Datasource.data:classpath:data.sql represents the SQL file that specifies the inserted data. Logging the output level of the log is configured below, where the two configurations about SQL are basically the same as the show-sql:true.

 
  Server:   port:  7900  Spring:   JPA:       strong> GENERATE-DDL:  false  Show-sql:  true  hibernate:   Ddl-auto:  None  DataSource:   platform:  mysql  url:  jdbc
    : Mysql://localhost:3306/microservice?useunicode=true&characterencoding=utf-8  Username:  Root  Password:  root  driver-class-name:  com.mysql.jdbc.Driver  Schema: classpath:schema.sql  data:  classpath:data.sql  Logging:   Level:  strong> root:  info  org.hibernate:  info  Org.hibernate.type.descriptor.sql.Basi Cbinder:  trace  org.hibernate.type.descriptor.sql.BasicExtractor:  trace  COM.ITMUC H:  DEBUG 

One of the rules in spring boot is that the startup class must be at the same level as the Controller, entity, repository. Otherwise there will be a problem.


After doing the above operation, we will start the micro-service, we just right-click on the Launch Class page, and in the right button menu, tap "Run microservicesimplepr ..." to start.


When you see the startup information as shown in the following figure, it indicates a successful start.


Start success, let's test what we just wrote the FindByID interface is good, we enter in the browser address bar: HTTP://LOCALHOST:7900/SIMPLE/1 can see the interface shown in the figure below, indicating that our service provider deployment succeeded ...


Third, service consumers

The second step is to build a service provider, now we build a service consumer, we still from HTTP/ Start.spring.io website Build Our microservices framework, we can notice that in dependencies this column only selected a Web, selected and finished, click the "Generate Project" button.

Clicking on the "Generate Project" button in the image above will bring up the download dialog, as shown in the image below, save as saved to the local disk.

After downloading, we unzip to the current folder, as shown in the figure below.

Below we import this consumer into the IntelliJ idea tool, we click File---->new------>module from Existing Sources ..., as shown in the figure below

In the popup dialog we select the Pom.xml file of the movie Micro Service we just pressed, then click "OK", as shown in the image below.

In the next two steps just click "Next" and then click "Finish" button to add the project to the IntelliJ idea tool, as shown in the figure below

Below we also create a new user class under the movie Micro Service, as shown in the following figure, we can see here we do not add annotations to the user class, because here we just consider it as a normal VO class, and the first microservices add JPA annotations because we have to The user class is configured as the entity class that corresponds to database table one by one, the primary key generation strategy, and so on.

Let's create a new controller class, as shown in the following figure, where we call the address of the first MicroServices interface in the FindByID method of the class and return a user object. This means that the movie API consumes the user Service API.

Let's change the configuration file, change the application.properties suffix name to. yml, and add the port configuration to the configuration file as shown in the following figure.

In this way, a simple service consumer code is finished, below we will start the service provider and service consumers, we need to go to the Service startup class page to start (the image below is the start of the movie service)

We will report a mistake when we start the movie Micro Service, as described below:

Description: Field resttemplate in Com.itmuch.cloud.controller.MovieController required a bean of type ' Org.springframework.web.client.RestTemplate ' that could isn't being found.
Action:
Consider defining a bean of type ' org.springframework.web.client.RestTemplate ' in your configuration.

This is because an instance of Resttemplate was not found, so in order to solve the problem, we added the resttemplate bean annotations in the movie's startup class, as shown in the following illustration

Then we restart the movie Micro Service, it can start normally, as shown in the figure below

After two microservices are started, we go to the controller interface of the movie micro Service to see if we can get the user object information, we enter the access address is: HTTP://LOCALHOST:7901/MOVIE/1, as shown in the figure below, you can see that Can normally get user's information, stating that our service consumers can consume the service provided by the service provider.

At this point, two of the simplest micro-services we are finished, but now the two micro-services are still a big problem, such as we in the service consumer hard-coded access path, which in the premise of the traditional framework of the problem (because the environment is relatively fixed), but the micro-service, IP, port is dynamic, So we can't hard code. Even if you put the access path to the configuration file, it can still be a lot of work (because of the possibility of a chain dependency, a microservices change, and possibly other microservices need to change). You may propose to use Nginx for load management, when the number of microservices is very large, using Nginx load balancing is also a difficult thing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.