springcloud2020
Daily Maxim
Learning your mind and understanding is useless—— "Confucian classics Grottoes"
Organize knowledge
String your previous things
How to learn at this stage
While learning new knowledge, don't forget to review yourself and your knowledge
My own things
- javaSE
- database
- Front end knowledge
- Servlet
- springboot
- Mybatis
- spring
- Maven
- Ajax
- dubbo+zookeeper
What I missed
- Http
Changes in standards
We learned about ssm before
Where is the core of our development
Java EE standard
Spring Java EE development standard
spring connects almost everything in our development. It is like a central integration
But slowly we found that he was really light?
- With the increasing amount of development
It made him no longer lightweight, so a new solution was born
New Java EE standard
Springboot Java EE develops new standards
It simplifies the cumbersome configuration and automatically helps us do a lot of things that need to be done repeatedly in the configuration,
Given us a default solution, we can understand boot as a spring plus version. It integrates many initiators, so that springboot gradually replaces ssm. Springboot has slowly become the best solution for Java EE, which is loved by countless enterprises
Whether it is the new standard or the old standard, its characteristics are unified: agreement is greater than configuration
At first
The program we are developing now is in the form of all in one. All modules are in one jar or war package
evolution
Then, with the evolution of the architecture, we gradually split the functions, and the code has not changed
However, once the concurrency is high, our machine can't implement the business normally
Now?
The solution came into being, and the micro service architecture
The function is split into multiple devices to solve the problem that the business cannot run normally due to performance
Four core issues of microservices:
- There are many services. How do users access the registry
- How to communicate in services: rpc
- So many services, service governance?
- What if the service hangs up?
For these problems, spring cloud is an ecosystem
Used to solve these four problems
-
Spring cloud netfix one-stop solution
api gateway, zuul component
Feign -- httpclinet -- HTTP communication mode
Service registration discovery: Eureka
Fuse mechanism: Hystrix
. . . .
-
Apache Dubbo zookeeper is semi-automatic and needs to integrate other people's
API does not exist. Find a third-party component or implement it yourself
Dubbo communication, high performance rpc framework
Service registration discovery: zookeeper
Fuse mechanism does not: with the help of Hystrix
-
Spring Cloud Alibaba's latest one-stop solution!
New concept: Service Grid! server mesh
The concept is the same:
- API
- http rpc
- Registration and discovery
- circuit breaker
Why does this happen? Because: the network is unreliable!
Microservices
- At present, there is no unified standard definition of microservices in the industry
- Microservice architecture is an architecture mode or an architecture style. It advocates that a single application is divided into a group of small services. Each service runs in its own independent process. Services coordinate and configure each other, advocate the final value for users, reflect the final value, and use lightweight communication mechanism to communicate with each other, Each service is built around a specific business and can be independently deployed in the production environment. In addition, try to avoid a unified and centralized service management mechanism. For a specific service, select appropriate languages and tools and align the construction according to the context. There can be a very lightweight centralized management to coordinate the business, It can be written in different languages or stored in different data
Let's understand it from the technical dimension
That is, the role of microservices is to solve a traditional project to the business (one-stop application) according to the business, it is divided into services one by one to completely decouple. Each micro service provides the functional services of a single business. One service does one thing. From a technical point of view, it is a small and independent processing process. The concept of class process can be started or destroyed independently and has its own independent database
Microservices and microservice architecture
Microservices
The emphasis is on the size of the service. What he focuses on is to specifically solve a problem and provide landing service applications, that is, the microservice projects or moudel in the idea
In the idea tool, maven is used to build independent small molds. Specifically, it uses small modules developed by springboot. Professional things are done by professional templates. Each module does one thing
The emphasis is on individual, and each individual completes a specific task or function!
Microservice architecture
A new architecture, Martin Fowler
2014 launch
- Microservice architecture is an architecture mode or an architecture style. It advocates that a single application is divided into a group of small services. Each service runs in its own independent process. Services coordinate and configure each other, advocate the final value for users, reflect the final value, and use lightweight communication mechanism to communicate with each other, Each service is built around a specific business and can be independently deployed in the production environment. In addition, try to avoid a unified and centralized service management mechanism. For a specific service, select appropriate languages and tools and align the construction according to the context. There can be a very lightweight centralized management to coordinate the business, It can be written in different languages or stored in different data
Disadvantages of microservices
advantage
- Single responsibility principle
- Each service is cohesive enough, small enough, and the code is easy to understand, which can focus on a specified business function and business requirements
- The development is simple and the development efficiency is improved. A service may be escaped and only do one thing
- Microservices can be developed independently by a small team consisting of 2 ~ 5 developers
- Microservices are loosely coupled and functionally meaningful services. They are independent in the development stage or deployment stage
- Microservices can be developed using different predictions
- It is easy for third-party integration. Microservices allow easy and flexible integration and automatic deployment through continuous integration tools, such as jenkins, hudson and bamboo
- Microservices are easy to be understood, modified and maintained by a developer, so that small teams can pay more attention to their work results. Value can be realized without cooperation
- Microservices allow you to take advantage of the latest technologies
- Microservices are just business logic code and will not mix html, css or other interfaces
- Each microservice has its own storage capacity. It can have its own database or a unified database
Disadvantages:
- Developers have to deal with the complexity of distributed systems
- Multi service operation and maintenance is difficult. With the increase of services, the operation and maintenance pressure is also increasing
- System deployment dependency
- Inter service communication cost
- Data consistency
- System integration test
- Performance monitoring
Microservice technology stack
Microservice Technology Entry | Landing technology |
---|---|
Service development | SpringBoot,Spring,SpringMVC |
Service configuration and management | Archius of netflix and diamond of Ali, etc |
Service registration and discovery | eureka,consul,zookeeper |
Service call | rest,rpc,grpc |
Service fuse | Hystrix, Envoy et al |
load balancing | RIbbon, nginx et al |
Service interface call (a simplified tool for the server to call services) | Feign et al |
Message queue | kafka,rabbitMQ,ActiveMQ |
Service configuration center management | SpringCloudconfig, chef, etc |
Service routing | Zuul et al |
Service monitoring | zabbix,Nagios,M ertrics,Specatator |
Full link tracking | Zipkin,Brave,Dapper |
Service deployment | DOCKER,openStack,kubernetes |
Data operation development package | Spring cloud stream (encapsulating sending and receiving messages with rides, rabbit, kafka, etc.) |
Event message bus | springcloud Bus |
Why do we choose spring cloud as the microservice architecture
1. Selection basis
- Overall solution and framework maturity
- Community heat
- Maintainability
- learning curve
2. What are the current microservice architectures of major companies
- Ali: dubbo+hfs
- JD: jsf
- Sina: Motan
- Dangdang: bubbox
Functional and service framework | Netflix/springCloud | Motan | grpc | thrift | Dubbo/dubbox |
---|---|---|---|---|---|
Functional positioning | Complete microservice framework | rpc framework, however, integrates zk or consumer to realize cluster environment and basic service registration and discovery | rpc framework | rpc framework | Service Framework |
Support rest | Yes, ribbon supports a variety of pluggable serialization options | no | no | no | no |
Support rpc | No (but compatible with dubbo) | yes | yes | yes | yes |
Support multiple languages | Support (rest form) | no | yes | yes | no |
load balancing | Support (server zuul + client ribbon), zuul service, dynamic routing, cloud load balancing, eureka for middle tier servers | Support (client) | no | no | Yes (client) |
Configure services | Netfix archhaius spring cloud config server centralized configuration | Yes (provided by zookeeper) | no | no | no |
Service call chain monitoring | Support, zuul, zuul provides edge services, api gateway | no | no | no | no |
High availability / fault tolerance | Support, server hystrix+ribbon | Support (client) | no | no | Support (client) |
Typical application cases | Netflix | sina | |||
Community activity | high | commonly | high | commonly | Re maintenance only started in 2017, which was interrupted for five years |
Learning difficulty | in | low | high | high | low |
Document richness | high | commonly | commonly | commonly | high |
other | Spring cloud bus brings more management endpoints to our applications | Support downgrade | netflix is developing and integrating grpc internally | idl definition | There are many companies practicing |
Spring cloud getting started overview
What is spring cloud?
springcloud provides a set of microservice solutions based on springboot, including service registration, discovery, configuration center and full link monitoring
Service network management, load balancing, fuse and other components, in addition to the highly abstract packaging of open-source components based on netflix, there are also some selection neutral 1 open-source components.
Taking advantage of the development convenience of springboot, springcloud cleverly simplifies the development of distributed system infrastructure. Springcloud provides developers with some tools to quickly build distributed systems, including configuration management, service discovery, circuit breaker, routing, micro agent, event bus, global lock, decision-making campaign, distributed session, etc, They can use the development style of spring boot to achieve one click deployment
Springboot does not make wheels repeatedly. It just combines the relatively mature service framework developed by various companies that can withstand the actual postgraduate entrance examination, encapsulates it through the springboot style, shields the complex configuration and implementation principle, and finally leaves a set of simple, easy to understand, easy to deploy and easy to maintain distributed system development kit for developers
springcloud is a one-stop solution under the distributed micro service architecture. It is a collection of landing technologies of various micro service architectures, commonly known as micro service platform
Relationship between springboot and springcloud
- springboot focuses on developing individual micro services quickly and easily
- springcloud focuses on the coordination and governance framework of global microservices. It integrates and manages individual microservices developed by springboot, and provides integrated services such as configuration management, service discovery, circuit breaker, routing, event bus, global lock, decision-making campaign, distributed session and so on
- Springboot can be used independently of springcloud to develop projects, but springcloud cannot be separated from springboot and belongs to dependency
- Spring boot focuses on developing individual micro services quickly and conveniently, and spring cloud focuses on the overall service governance framework
Dubbo and springcloud technology selection
Distributed + service governance Dubbo
Currently mature Internet Architecture: application service splitting + message oriented middleware
Comparison between Dubbo and springcloud
dubbo should be that after the watch stop, the community is not active, dying, and the future is unknown
The community of springcloud is very active and in its prime,
Comparison chart:
The biggest difference: spring cloud abandons Dubbo's rpc communication and adopts http based rest
Strictly speaking, the two methods have their own advantages and disadvantages. To a certain extent, the latter sacrifices the performance of service invocation, but also avoids the problems caused by native rpc. rest is more flexible than rpc. The dependence of service providers and callers only depends on one July, and there is no strong dependence at the service level. This is more appropriate in the micro service environment that emphasizes fast fireworks
Difference between brand machine and assembly machine
springcloud (brand machine):
It is obvious that the functions of spring cloud are much more powerful than dubbo, with a wider coverage. Moreover, as a spring Star project, it can also be perfectly integrated with other spring projects.
dubbo (assembly machine):
Building a microservice architecture with dubbo is like assembling a computer. We have a high degree of freedom of choice in all links, but the final result may be that a memory module is not lit, which is always not reassuring. However, if you are a master, these are not problems,
springcloud is like a brand-name machine. Under the integration of spring source, it has done a lot of compatibility tests to ensure that the machine has higher stability. However, if you want to use something other than the original components, you need to know enough about its foundation,
Community support and renewal
Most importantly, dubbo has stopped for five years. Although it has been restarted in 17 years, it needs to develop its own expansion and upgrading for the needs of technological development. For example, dubbox is obviously inappropriate for many small and medium-sized software organizations that want to adopt micro services. Small and medium-sized companies do not have so powerful technology to modify dubbo's source code + a complete set of surrounding solutions. Not every company has been tested in Alibaba's Daniel + real online production environment
summary
dubbo, the once popular rpc framework in China, has made many users happy after restarting maintenance, but at the same time, there should be doubts. Can dubbo keep up with the rapid development of the times? What are the differences between dubbo and spring cloud? Will there be relevant measures to ensure the subsequent update frequency of dubbo
dubbo is an rpc focused framework. The goal of spring cloud is a one-stop solution under the microservice architecture
Design mode + micro service splitting idea: you can lead technical talents who are not necessarily good at expression. Soft power is the key point in the workplace. You may not have good technology, but your design thinking, architecture understanding and expression ability enable you to become a team leader who only knows technical talents,
Spring cloud Download
Different versions of spring cloud
Named after the London underground station and characters
Here are a few documents you need to know
Chinese documentation of springcloud: https://www.springcloud.cc/spring-cloud-dalston.html
Community official website: http://docs.springcloud.cn/
The above theoretical content is linked to the code, and light capital is also a very important thing in many interviews
Get started
- We use a payment module as a general case of microservice in the style of rest
- Recall what ssm learned
- Architecture review of maven subcontracting module
A parent project has multiple sub modules
Do it!
Large version description of spring cloud
springboot | springcloud | relationship |
---|---|---|
1.2.x | angel | Compatible with boot1 2.x |
1.3.x | brixton version | Compatible with spring 1 3, also compatible with 1.4 |
1.4.x | camden version | Compatible with spring 1 4, also compatible with 1.5 |
1.5.x | dalston version | Compatible with spring 1 5. Incompatible with 2.0 x |
1.5.x | edgware | Compatible with spring 1 5, incompatible with 2.0 |
2.0.x | finchley | Compatible with spring 2 0, incompatible with 1.5 |
2.1.x | greenwich |
By 2020, we will find that technologies will change from generation to generation, some technologies will slowly stop updating and maintenance, and new and more comprehensive solutions will keep up with the rapid development of the times
cloud project construction
We use maven aggregation project as the parent project
Writing sub modules in it can mainly solve a problem
It is the unified management of dependent versions of sub modules
Here, we will use dependency management + properties to control the version
The following figure is a review of some knowledge about dependency management
Parent project pom
<?xml version="1.0" encoding="UTF-8"?> <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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.hyc.springcloud</groupId> <artifactId>cloud2020</artifactId> <version>1.0-SNAPSHOT</version> <modules> <module>cloud-provider-payment8001</module> </modules> <packaging>pom</packaging> <!-- unified management jar Package version --> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <junit.version>4.12</junit.version> <log4j.version>1.2.17</log4j.version> <lombok.version>1.16.18</lombok.version> <mysql.version>8.0.11</mysql.version> <druid.version>1.1.16</druid.version> <mybatis.spring.boot.version>1.3.0</mybatis.spring.boot.version> </properties> <!-- After the sub module inherits, it provides the following functions: locking the version+son modlue Do not write groupId and version --> <dependencyManagement> <dependencies> <!--spring boot 2.2.2--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.2.2.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <!--spring cloud Hoxton.SR1--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Hoxton.SR1</version> <type>pom</type> <scope>import</scope> </dependency> <!--spring cloud alibaba 2.1.0.RELEASE--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>2.1.0.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.spring.boot.version}</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> <optional>true</optional> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> <addResources>true</addResources> </configuration> </plugin> </plugins> </build> </project>
After finishing this, we can write sub modules
Payment module, service provider
Build cloud provider payment8001
In the study of spring boot, we found that the construction of a module also has traces to follow
- Create a moudle
- Write pom and import dependency
- Write boot configuration file yml
- Main startup class
- Write business class
- test
Generally speaking, these are the steps
Then let's follow
The first is to create a module
Then introduce the required dependencies
<?xml version="1.0" encoding="UTF-8"?> <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"> <parent> <artifactId>cloud2020</artifactId> <groupId>com.atguigu.springcloud</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>cloud-provider-payment8001</artifactId> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
Then write the relevant configuration file application Yml
server: port: 8001 spring: application: name: cloud-payment-service datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: org.gjt.mm.mysql.Driver url: jdbc:mysql://localhost:3306/db2019?useUnicode=true&characterEncoding=utf-8&useSSL=false username: root password: 123456 mybatis: mapperLocations: classpath:mapper/*.xml type-aliases-package: com.atguigu.springcloud.entities
Write business class
Entity class
package com.atguigu.springcloud.entities; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Data @AllArgsConstructor @NoArgsConstructor public class Payment implements Serializable { private Long id; private String serial; }
Json package CommonResult
package com.atguigu.springcloud.entities; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class CommonResult <T>{ private Integer code; private String message; private T data; public CommonResult(Integer code,String message){ this(code,message,null); } }
mapper and mapping file
mapper interface
package com.hyc.cloud.mapper; import com.hyc.cloud.pojo.payment; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @Mapper public interface PaymentMapper { public int create(payment payment); public payment getPaymentByid(@Param("id") long id); }
Corresponding mapping file
<?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.hyc.cloud.mapper.PaymentMapper"> <insert id="create" parameterType="com.hyc.cloud.pojo.payment" useGeneratedKeys="true" keyProperty="id"> insert into db01.paymemt (serial) values (#{name}); </insert> <select id="getPaymentByid" resultType="com.hyc.cloud.pojo.payment" parameterType="long" resultMap="BaseResultMap"> select * from paymemt where id = #{id}; </select> <resultMap id="BaseResultMap" type="com.hyc.cloud.pojo.payment"> <id column="id" property="id" jdbcType="BIGINT"/> <id column="serial" property="serial" jdbcType="VARCHAR"/> </resultMap> </mapper>
Service layer
package com.atguigu.springcloud.service; import com.atguigu.springcloud.entities.Payment; import org.apache.ibatis.annotations.Param; public interface PaymentService { public int create(Payment payment); //write public Payment getPaymentById(@Param("id") Long id); //read }
Implementation class
package com.atguigu.springcloud.service.impl; import com.atguigu.springcloud.dao.PaymentDao; import com.atguigu.springcloud.entities.Payment; import com.atguigu.springcloud.service.PaymentService; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class PaymentServiceImpl implements PaymentService { @Resource private PaymentDao paymentDao; public int create(Payment payment){ return paymentDao.create(payment); } public Payment getPaymentById( Long id){ return paymentDao.getPaymentById(id); } }
Finally, the controller
package com.hyc.cloud.controller; import com.hyc.cloud.pojo.CommonResult; import com.hyc.cloud.pojo.payment; import com.hyc.cloud.service.PaymentService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController @Slf4j public class PaymentController { @Resource private PaymentService paymentService; @PostMapping("payment/create") public CommonResult create(payment payment){ int result = paymentService.create(payment); log.info("****New results:"+result); if (result>0){ return new CommonResult(200,"Insert database succeeded",result); }else { return new CommonResult(444,"Insert database failed",null); } } @GetMapping("payment/get/{id}") public CommonResult getPaymentByid(@PathVariable("id") long id){ payment payment = paymentService.getPaymentByid(id); log.info("****New results:"+payment); if (payment!=null){ return new CommonResult(200,"query was successful",payment); }else { return new CommonResult(444,"No corresponding record, failed to query id"+id,null); } } }
Write the main startup class
package com.hyc.cloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class paymentMain8001 { public static void main(String[] args) { SpringApplication.run(paymentMain8001.class,args); } }
Just test
Payment module, consumer
Go through the process and we'll speed up
New consumer sub module
cloud-consumer-order80
Modify pom file
<?xml version="1.0" encoding="UTF-8"?> <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"> <parent> <artifactId>cloud2020</artifactId> <groupId>com.hyc.springcloud</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>cloud-consumer-order80</artifactId> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
The configuration file consumer is very simple, that is, configure the port number
server: port: 80
Then copy the entity class to the consumer project
So think about a question
Now we are no longer a single project but two projects. What if we transfer to the interface???
There are many template s in springboot for us to use
What we need to use here is the resttemplate
It is similar to httpclient in network programming
Here, we need to write a config class. We can create new whatever springboot needs
@Configuration public class orderConfig { @Bean public RestTemplate restTemplate(){ return new RestTemplate(); } }
With this, we can call resttemplate in the consumer
Because we are consumers, we just need to know how to use the service
Here we write the controller
package com.hyc.cloud.controller; import com.hyc.cloud.pojo.CommonResult; import com.hyc.cloud.pojo.payment; import io.micrometer.core.instrument.Meter; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; @RestController public class orderContorller { @Resource private RestTemplate restTemplate; public final static String PAYMENT_URL = "http://localhost:8001 "; / / the address of the service provider (it will be replaced with application.name later in load balancing) @GetMapping("/consumer/payment/create") public CommonResult create(payment payment){ return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class); } @GetMapping("/consumer/payment/get/{id}") public CommonResult getPament(@PathVariable("id") long id){ return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+ id,CommonResult.class); } }
Start the test here
Do you think it's over?
Of course not
Here is the problem of inserting data
Only the self incremented primary key has no content
At this time, we have to go back to the service provider
Add the annotation @ requestbody before the new object parameter, and the host will test again to solve it
@PostMapping("payment/create") public CommonResult create(@RequestBody payment payment){ int result = paymentService.create(payment); log.info("****New results:"+result); if (result>0){ return new CommonResult(200,"Insert database succeeded",result); }else { return new CommonResult(444,"Insert database failed",null); } }
At this time, the database is also added successfully
Here, take the payment module as an example, and the experience demo is over
Epilogue
I hope my study notes can help the students who are studying while improving themselves