Microservices are:
The microservice architecture is an architecture pattern, or architectural style, that promotes the partitioning of a single application into a set of small services, each running in its own separate process, which coordinate, configure and provide end value to users. Services use lightweight communication mechanisms to communicate with each other. Each service is built around a specific business and can be deployed independently in a production environment. In addition, unified, centralized service management mechanisms should be avoided as much as possible. For a specific service, according to business context, select the appropriate language, and build it with tools. There can be a very lightweight centralized management to coordinate these services, you can use different languages to write services, It is also possible to use a different data store;
To put it simply, it is to split a business into small modules and completely decouple them. Each microservice provides a single business function service, a service does one thing, and each service can have a separate startup. Or destroy, have your own database.
advantage:
- Each service is cohesive enough, small enough, and the code is easy to understand, so that it can focus on a specified business function or business requirement;
- The development is simple and the development efficiency is improved. A service may be dedicated to only one thing;
- Microservices can be developed independently by a small team consisting of 2-5 developers;
- Microservices are loosely coupled, functionally meaningful services that are independent whether they are in the development phase or deployment phase.
- Microservices can be developed in different languages.
- Easy to integrate with third parties, microservices allow an easy and flexible way to integrate automatic deployment, through continuous integration tools such as jenkins, Hudson, bamboo microservices are easy to be understood, modified and maintained by a developer, so that small teams can focus more on their own Results of the work.
- Value does not need to be realized through collaboration. Microservices allow you to leverage the latest technologies in fusion.
- Microservices are just code for business logic, not mixed with HTML, CSS or other interfaces
- Each microservice has its own storage capabilities, it can have its own database, or it can have a unified database
shortcoming:
- Developers deal with the complexities of distributed systems
- It is difficult to operate and maintain multiple services. With the increase of services, the pressure of operation and maintenance also increases. System deployment dependencies
- Inter-service communication cost
- data consistency
- system integration testing
- Performance monitoring.....
Getting started with springCloud:
SpringCloud, based on SpringBoot, provides a set of micro-service solutions including service registration and discovery, configuration center, full-link monitoring, service gateway, load balancing, fusers, and other components. In addition to highly abstract encapsulation of NetFlix-based open source components, there are also selected neutral open source components.
Using SpringCloud's development convenience, SpringBoot cleverly simplifies the development of distributed system infrastructure. SpringCloud provides developers with tools to quickly build distributed systems, including configuration management, service discovery, circuit breakers, routing, micro-agents, Event bus, global lock, decision campaign, distributed session, etc. They can all be started and deployed with one click using SpringBoot's development style.
SpringBoot does not re-create wheels. Instead, it combines the mature service frameworks developed by various companies to withstand the actual research and research, and re-encapsulates them in SpringBoot style, masking out the complex configuration and implementation principles. Finally, it leaves developers with a set of distributed system development toolkits that are easy to understand, deploy and maintain.
SpringBoot focuses on the rapid and convenient development of a single individual microservice, and SpringCloud focuses on the global service governance framework
Rest Microservice Construction
Steps to build the project
- import dependencies
- write configuration file
- Enable this feature @EnableXXXXX
- Configuration class (depending on the situation, sometimes you have to write, sometimes you don't)
First create the maven project of the parent project springCloud
and add in pom
<!-- Packaging method-->
<packaging>pom</packaging>
<!-- The version of the configuration package-->
<properties>
<junit.version>4.12</junit.version>
<log4j.version>1.2.17</log4j.version>
<lombok.version>1.16.18</lombok.version>
</properties><dependencyManagement> <dependencies> <!-- spring-cloud-dependencies --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>2021.0.4</version> <type>pom</type> <scope>import</scope> </dependency> <!-- spring-boot-dependencies --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.2.1.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <!-- mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!-- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.6</version> </dependency> <!-- mybatis-spring-boot-starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> </dependency> </dependencies> </dependencyManagement>
delete the src folder
Create module springcloud-api
pom.xml
<dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies>
Create dept pojo class
package com.xflsh.springcloud.pojo; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.io.Serializable; /* Chained writing: Dept dept = new Dept() dept.setDeptno(11L).setDname("school").setDb_source("DB01"); **/ @NoArgsConstructor @Data @Accessors(chain = true) //chain writing public class Dept implements Serializable {//Dept(entity class) orm mysql->Dept(surface) Class table relationship mapping private Long deptno; //primary key private String dname; //Department name //Which database is it from, because the microservice architecture can correspond to one database for one service, and the same information is stored in multiple different databases private String db_source; public Dept(String dname) { this.dname = dname; } }
Create the server module springcloud-provider-dept-8001
pom.xml
<dependencies> <!-- eureka--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> <version>1.4.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <!--Introducing a custom module, we can use the classes in this module--> <dependency> <groupId>org.example</groupId> <artifactId>springcloud-api</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-test</artifactId> </dependency> <!-- spring-boot-devtools --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> </dependencies>
application.yml
server: port: 8001 #configuration of mybatis mybatis: config-location: classpath:mybatis/mybatis-config.xml type-aliases-package: com.xflsh.springcloud.pojo mapper-locations: classpath:mybatis/mapper/*.xml #spring related configuration spring: application: name: springcloud-provider-dept datasource: type: com.alibaba.druid.pool.DruidDataSource # data source driver-class-name: org.gjt.mm.mysql.Driver # mysql driver url: jdbc:mysql://localhost:3306/db01?useUnicode=true&characterEncoding=utf-8 #Database name username: root password: a1814995041
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <!--Enable L2 cache--> <setting name="cacheEnabled" value="true"/> </settings> </configuration>
DeptDao.class
package com.xflsh.springcloud.service; import com.xflsh.springcloud.pojo.Dept; import org.springframework.stereotype.Service; import java.util.List; @Mapper public interface DeptService { public boolean addDept(Dept dept); //add a department public Dept queryById(Long id); //according to id Inquiry Department public List<Dept> queryAll(); //Inquire all departments }
DeptMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.xflsh.springcloud.dao.DeptDao"> <insert id="addDept" parameterType="Dept"> insert into dept (dname,db_source) values (#{dname},DATABASE()); </insert> <select id="queryById" resultType="Dept" parameterType="Long"> select deptno,dname,db_source from dept where deptno = #{deptno}; </select> <select id="queryAll" resultType="Dept"> select deptno,dname,db_source from dept; </select> </mapper>
DeptService.class
package com.xflsh.springcloud.service; import com.xflsh.springcloud.pojo.Dept; import org.springframework.stereotype.Service; import java.util.List; public interface DeptService { public boolean addDept(Dept dept); //add a department public Dept queryById(Long id); //according to id Inquiry Department public List<Dept> queryAll(); //Inquire all departments }
DeptServiceImpl.class
package com.xflsh.springcloud.service.impl; import com.xflsh.springcloud.pojo.Dept; import com.xflsh.springcloud.dao.DeptDao; import com.xflsh.springcloud.service.DeptService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class DeptServiceImpl implements DeptService { @Autowired private DeptDao deptDao; @Override public boolean addDept(Dept dept) { return deptDao.addDept(dept); } @Override public Dept queryById(Long id) { return deptDao.queryById(id); } @Override public List<Dept> queryAll() { return deptDao.queryAll(); } }
DeptController.class
package com.xflsh.springcloud.controller; import com.xflsh.springcloud.pojo.Dept; import com.xflsh.springcloud.service.DeptService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/dept") public class DeptController{ @Autowired DeptService deptservice; // @RequestBody // If the parameter is placed in the request body and passed into the background, then the background uses@RequestBody to receive @PostMapping("/add") public boolean addDept(@RequestBody Dept dept) { return deptservice.addDept(dept); } @GetMapping("/get/{id}") public Dept get(@PathVariable("id") Long id) { return deptservice.queryById(id); } @GetMapping("/list") public List<Dept> queryAll() { return deptservice.queryAll(); } }
Write the launcher DeptProvider8001 .class
package com.xflsh.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DeptProvider8001 { public static void main(String[] args){ SpringApplication.run(DeptProvider8001.class,args); } }
Visit http://localhost:8001/dept/list to get data
Create consumer module springcloud-consumer-dept-80
<artifactId>springcloud-consumer-dept-80</artifactId> <description>Departmental Microservice Consumer</description> <dependencies> <dependency> <groupId>org.example</groupId> <artifactId>springcloud-api</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--hot deployment--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> </dependencies>
application.yml
server: port: 80
Write the configuration class configBean
package com.xflsh.springcloud.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class configBean { // RestTemplate Provides a variety of convenient access to remote Http service method, is a simple and convenient access restful service template class, yes Spring provided for access Rest Client Template Toolset for Services // use RestTemplate access restful The interface is very simple, rude and mindless //(url,requsetMap,ResponseBean.class) These three parameters represent REST request address, request parameters, // Http The type of object to which the response conversion is converted @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } }
DeptConsumerController .class
package com.xflsh.springcloud.controller; import com.xflsh.springcloud.pojo.Dept; import org.springframework.beans.factory.annotation.Autowired; 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 java.util.List; @RestController public class DeptConsumerController { //Understanding: Consumers, should not have service Floor // use RestTemplate access restful The interface is very simple, rude and mindless // (url,requestMap,ResponseBean.class) These three parameters represent // REST request address, request parameters, Http The type of object to which the response conversion is converted @Autowired private RestTemplate restTemplate; private static final String REST_URL_PREFIX = "http://localhost:8001"; @RequestMapping("/consumer/dept/add") public boolean add(Dept dept){ return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add",dept,Boolean.class); } @RequestMapping("/consumer/dept/get/{id}") public Dept get(@PathVariable("id") Long id){ return restTemplate.getForObject(REST_URL_PREFIX+"/dept/get/"+id,Dept.class); } @RequestMapping("/consumer/dept/list") public List<Dept> list(){ return restTemplate.getForObject(REST_URL_PREFIX+"/dept/list",List.class); } }
Startup class DeptConsumer80 .class
package com.xflsh.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DeptConsumer80 { public static void main(String[] args) { SpringApplication.run(DeptConsumer80.class,args); } }
Accessing http://localhost/consumer/dept/list will give the same data as the provider, because port 80 can be omitted without localhost
knowledge blind spots;
RestTemplate provides a variety of convenient methods for accessing remote Http services. It is a simple and convenient access to restful service template class. It is a client-side template toolset provided by Spring for accessing Rest services. Using RestTemplate to access the restful interface is very simple, rude and mindless (url, requsetMap, ResponseBean.class) These three parameters represent the REST request address, request parameters, Http response conversion is converted to the object type