Spring Cloud Learning Case (1): Service Providers and Consumers

    This series of blogs (Spring Cloud Learning Cases) is a blogger who sorted out the case parts in the book "Spring Cloud and Docker Microservice Architecture in Practice" by Mr. Zhou Li, and made some small changes and added some own elements, recording the detailed steps.

    Because it is a case sharing, too much theoretical knowledge will not be repeated, and only the actual combat process will be emphasized.

    The first case is about a simple service provider and consumer. This case is mainly to let everyone resume the concept of microservices.

Case description

   A user initiates a ticket purchase request through the client, which is first sent to the movie microservice. The movie microservice needs to know the user's information, and then sends the request to the user microservice. The relationship is as follows:


case analysis

   User microservice: service provider, which provides query user information based on id. This is done using mybatis.

   Movie microservice: service consumer, accepts the id parameter in the user request, and calls the service provided by the user microservice to query user information based on id. Use restTemplate to make rest calls.

Case realization

1. Service Provider

Step 1: Create a maven project


Step 2: Write pom.xml

    The service uses mybatis as the dao layer framework, druid as the connection pool, and mysql database.

<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>

   <groupId>com.cgg.springcloud</groupId>

   <artifactId>demo01-user-provider</artifactId>

   <version>0.0.1-SNAPSHOT</version>

   <name>demo01-user-provider</name>

   <description>Service Provider: User Microservice</description>

   <parent>

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-starter-parent</artifactId>

      <version>1.5.10.RELEASE</version>

   </parent>

   <properties>

      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

      <java.version>1.8</java.version>

   </properties>

   <dependencyManagement>

      <dependencies>

         <dependency>

            <groupId>org.springframework.cloud</groupId>

            <artifactId>spring-cloud-dependencies</artifactId>

            <version>Edgware.SR3</version>

            <type>pom</type>

            <scope>import</scope>

         </dependency>

      </dependencies>

   </dependencyManagement>

   <dependencies>

      <!-- springboot integrated web development -->

      <dependency>

         <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter-web</artifactId>

      </dependency>

      <!-- springboot integration druid -->

      <dependency>

         <groupId>com.alibaba</groupId>

         <artifactId>druid-spring-boot-starter</artifactId>

         <version>1.1.9</version>

      </dependency>

      <!-- springboot integrates mysql -->

      <dependency>

         <groupId>mysql</groupId>

         <artifactId>mysql-connector-java</artifactId>

      </dependency>

      <!-- springboot integrates mybatis -->

      <dependency>

         <groupId>org.mybatis.spring.boot</groupId>

         <artifactId>mybatis-spring-boot-starter</artifactId>

         <version>1.3.2</version>

      </dependency>

   </dependencies>

</project>

Step 3: Database Preparation

  • Create data table t_user
CREATETABLE `t_user` (

  `id` bigint(20) unsigned NOTNULL AUTO_INCREMENT,

  `username` varchar(32)NOTNULL,

  `name` varchar(32)NOTNULL,

  `age` int(3)NOTNULL,

  `balance` decimal(10,2)NOTNULL,

  PRIMARYKEY(`id`)

) ENGINE=InnoDBAUTO_INCREMENT=4DEFAULT CHARSET=utf8;

  • Insert three test data
INSERTINTO `t_user` VALUES(1,'damo','达摩',20,100.00);

INSERTINTO `t_user` VALUES(2,'mulan','花木兰',22,100.00);

INSERTINTO `t_user` VALUES(3,'daxiaojie','Sun Shangxiang',18,100.00);

Step 4: Configure the data source

    Create application.yml file in resources. It is also possible to create a properties file.

server:
 port: 9001
#==================================
# data source configuration
# ==================================
spring:
 datasource:
   druid:
     url: jdbc:mysql:///springcloud
     username: root
     password: root

Step 5: Preparing the Entity

package com.cgg.springcloud.demo1.pojo;

publicclass User {

   private Long id;

   private String username;

   private String name;

   private Integer age;

   private Double balance;

  

   public Long getId() {

      returnid;

   }

   publicvoid setId(Long id) {

      this.id = id;

   }

   public String getUsername() {

      returnusername;

   }

   publicvoid setUsername(String username) {

      this.username = username;

   }

   public String getName() {

      returnname;

   }

   publicvoid setName(String name) {

      this.name = name;

   }

   public Integer getAge() {

      returnage;

   }

   publicvoid setAge(Integer age) {

      this.age = age;

   }

   public Double getBalance() {

      returnbalance;

   }

   publicvoid setBalance (Double balance) {

      this.balance = balance;

   }

}

Step 6: Writing the DAO layer

  • mapper interface
package com.cgg.springcloud.demo01.mapper;

importcom.cgg.springcloud.demo01.pojo.User;

publicinterface UserMapper {

   // Query user information by id

   UserselectUserById(Long id);

}

  • UserMapper.xml file 
<?xml version="1.0"encoding="UTF-8"?>

<!DOCTYPE mapper

PUBLIC "-//mybatis.org//DTDMapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.cgg.springcloud.demo01.mapper.UserMapper">

   <!-- Query user information by id-->

   <select id="selectUserById"parameterType="long" resultType="com.cgg.springcloud.demo01.pojo.User">

      select*

      fromt_user

      whereid = #{id}

   </select>

</mapper>

Step 7: Writing the Service Layer

  • interface
package com.cgg.springcloud.demo01.service;

importcom.cgg.springcloud.demo01.pojo.User;

publicinterface UserService {

   // Query user information by id

   UserselectUserById(Long id);

}

  • Implementation class
packagecom.cgg.springcloud.demo01.service.impl;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.stereotype.Service;

importorg.springframework.transaction.annotation.Transactional;

importcom.cgg.springcloud.demo01.mapper.UserMapper;

import com.cgg.springcloud.demo01.pojo.User;

importcom.cgg.springcloud.demo01.service.UserService;

@Service

@Transactional

publicclass UserServiceImpl implements UserService{


   @Autowired

   private UserMapper userMapper;

   @Override

   public User selectUserById(Long id) {

      returnuserMapper.selectUserById(id);

   }

}

Step 8: Writing the Controller Layer

packagecom.cgg.springcloud.demo01.controller;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.web.bind.annotation.PathVariable;

importorg.springframework.web.bind.annotation.RequestMapping;

importorg.springframework.web.bind.annotation.RequestMethod;

importorg.springframework.web.bind.annotation.RestController;

importcom.cgg.springcloud.demo01.pojo.User;

import com.cgg.springcloud.demo01.service.UserService;


@RestController

@RequestMapping("/user")

publicclass UserController {

   @Autowired

   private UserService userService;

   @RequestMapping(value = "/{id}", method = RequestMethod.GET)

   public User selectUserById(@PathVariable Long id){

      returnuserService.selectUserById(id);

   }

}

Step 9: Start the class writing

   Note that automatic scanning of the mapper interface is required

package com.cgg.springcloud.demo01;

importorg.mybatis.spring.annotation.MapperScan;

importorg.springframework.boot.SpringApplication;

importorg.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication

@MapperScan("com.cgg.springcloud.demo01.mapper")

publicclass UserProviderApplication {

   publicstaticvoid main(String[] args) throws Exception {

      SpringApplication.run(UserProviderApplication.class, args);

   }

}

Step 10: Test

   test url: localhost:9001/user/1


2. Serve consumers

Step 1: Create a maven project


Step 2: Write pom.xml

   Because the movie microservice simply uses restTemplate to call the interface of the user microservice. So just add the dependencies of springboot to integrate web development.

<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">

 <modelVersion>4.0.0</modelVersion>

 <groupId>cn.cgg.springcloud</groupId>

 <artifactId>demo01-movie-consumer</artifactId>

 <version>0.0.1-SNAPSHOT</version>

 <name>demo01-movie-consumer</name>

 <description>Service Consumer: Movie Microservice</description>

 <parent>

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-starter-parent</artifactId>

      <version>1.5.10.RELEASE</version>

   </parent>

   <properties>

      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

      <java.version>1.8</java.version>

   </properties>

   <dependencyManagement>

      <dependencies>

         <dependency>

            <groupId>org.springframework.cloud</groupId>

            <artifactId>spring-cloud-dependencies</artifactId>

            <version>Edgware.SR3</version>

            <type>pom</type>

            <scope>import</scope>

         </dependency>

      </dependencies>

   </dependencyManagement>

   <dependencies>

      <!-- springboot integrated web development -->

      <dependency>

         <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter-web</artifactId>

      </dependency>

   </dependencies>

</project>

Step 3: Create User Entity

   The user entity in the consumer is the same as the user entity in the provider. In actual development, pojo is generally regarded as a separate project, and is packaged into a jar for other projects to rely on.

package com.cgg.springcloud.demo01.pojo;

public class User {
	private Long id;
	private String username;
	private String name;
	private Integer age;
	private Double balance;
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Double getBalance() {
		return balance;
	}
	public void setBalance(Double balance) {
		this.balance = balance;
	}
}

Step 4: Write the startup class

   Because the startup class is also a configuration class. @SpringBootApplication is a composite annotation. Register an instance of restTemplate in the startup class.

package com.cgg.springcloud.demo01;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class MovieConsumerApplication {
	
	// Register restTemplate in spring container
	@Bean(name = "restTemplate")
	public RestTemplate getRestTemplate(){
		return new RestTemplate();
	}
	
	public static void main(String[] args) throws Exception {
		SpringApplication.run(MovieConsumerApplication.class, args);
	}
	
}

Step 5: Write the controller

   Use restTemplate to call the provider's interface.

package com.cgg.springcloud.demo01.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.cgg.springcloud.demo01.pojo.User;

@RestController
@RequestMapping("/movie")
public class MovieController {
	private static final String GET_USERINFO = "http://localhost:9001/user/";
	
	@Autowired
	private RestTemplate restTemplate;
	
	@GetMapping("/user/{id}")
	public User getUserInfo(@PathVariable Long id){
		return restTemplate.getForObject(GET_USERINFO + id, User.class);
	}
	
}

Step 6: Configure application.yml

   Create an application.yml file under resources. Configure the project startup port. Separate from the provider.

server:
  port: 9002

Step 7: Test

   测试url:http://localhost:9002/movie/user/1
    The first study case of Spring Cloud is finished. Through this case, everyone mainly understands the basic idea of ​​microservices.
    Case github source code: https://github.com/xiecheng310/springcloud
https://github.com/xiecheng310/springcloud.git
https://github.com/xiecheng310/springcloud.git
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324685633&siteId=291194637