IDEA builds SpringCloud project [super detailed steps]

I. Introduction

The so-called microservices are to split the entire business module into multiple small modules that perform their own duties, to achieve the principle of single responsibility, not to repeatedly develop the same business code, and to achieve high cohesion and low coupling in the true sense. At the same time, microservices can expose interfaces to the outside world for use by other microservices.

If we initiate an http request in service A to service B, then we can realize remote calling of microservices. (restTemplate's getForObject method can initiate a request to the browser)
This method seems feasible, but coupling the url path and Java code together does not comply with the opening and closing principle. So the Eureka registration center appeared.

Every microservice needs to do one thing at the moment it starts, which is to register its service information with Eureka, such as service name, service port, etc. When other microservices want to call another service, they can directly go to Eureka to pull the information.
At the same time, in order to avoid that the pulled service has hung up, our serviceIt will send a heartbeat to Eureka every 30 seconds to prove that it is still alive. If it stops beating for one day, Eureka will remove it from the registration list.

如果存在多个服务提供者,服务消费者就会利用负载均衡算法,从服务列表中挑选一个!

2. Project construction

1. Database preparation

Here we need to prepare two databases. The user service and the order service each have their own databases.

CREATE TABLE USER (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20) NOT NULL,
phone VARCHAR(15) NOT NULL,
address VARCHAR(50) NOT NULL
);

INSERT INTO USER VALUES (1, "栈老师不回家", 13299075426, "山西省大同市")
INSERT INTO USER(NAME, phone, address) VALUES ("肖恩", 18834267011, "山西省太原市")
INSERT INTO USER(NAME, phone, address) VALUES ("李华", 12481076533, "山西省运城市")

Insert image description here

CREATE TABLE orders (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(30) NOT NULL,
price INT NOT NULL,
user_id INT NOT NULL REFERENCES USER(id)
)

INSERT INTO orders VALUES (1, "可乐鸡翅", 32, 1);
INSERT INTO orders(NAME, price, user_id) VALUES("冰镇啤酒", 12, 1);
INSERT INTO orders(NAME, price, user_id) VALUES("草莓冰激凌", 8, 2);
INSERT INTO orders(NAME, price, user_id) VALUES("狼牙土豆", 10, 3);

Insert image description here

2. Create a parent project

① It is still a SpringBoot project, select Spring Web dependency

Insert image description here

Insert image description here

② Delete the src directory and the two files starting with mvnw

Insert image description here

③ Add the packaging tag and SpringCloud version to the pom file, and modify the SpringBoot version

Insert image description here

④Introduce mysql and mybatis dependencies for subsequent use

Insert image description here

⑤ Add SpringCloud dependency library, so you don’t need to specify the version when using subsequent sub-modules.

Insert image description here

3. Create a registration center

① Create a new module on the parent project

Insert image description here

② Select Eureka Server

Insert image description here

③ Modify the content of the parent tag of the submodule to point to the parent project

Insert image description here

因为父模块中已经指定了 SpringCloud 的版本,所以子模块不需要再重复写!

④ Add the submodule in the parent pom

Insert image description here

⑤ Because the subclass will inherit the dependencies of the parent class, the redundant dependencies in the subclass can be deleted and what is needed will be added later.

Insert image description here

⑤ Write application.yml file

#服务端口,随便起
server:
  port: 11011
#服务名称
spring:
  application:
    name: eurekaserver
  datasource:
    url: jdbc:mysql:///ZXEdb?serverTimezone=UTC
    username: root
    password: 856724bb
    driver-class-name: com.mysql.cj.jdbc.Driver

#eureka地址
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:11011/eureka/
    register-with-eureka: false
    fetch-registry: false
    

Insert image description here

服务名称和 eureka 地址的配置我们可以认为是服务注册的配置,而 eureka 自己也是一个微服务,所以在服务启动的时候,它也会把自己注册到 eureka 上!

⑥ Add the @EnableEurekaServer annotation to the startup class

Insert image description here

⑦ Enter http://localhost:11011/, and the following interface will appear, indicating that Eureka is successfully created.

Insert image description here

4. Service registration

Scenario:
Create an order service and a user service, and register them both in eureka. User needs to be used in order, so order at this time is the consumer and user is the provider.

For service registration, we only need to complete two steps:
① Introduce the spring-cloud-starter-netflix-eureka-client dependency;
② Configure the service name and eureka address in the yml file.

eureka 服务的依赖是 server,其余微服务都是 client!

① Create order service and user service

Insert image description here

②Introduce eureka client dependency

Insert image description here

Insert image description here

③ Add the submodule in the parent pom

Insert image description here

④Write yml configuration file

#服务端口,随便起
server:
  port: 8081
#服务名称
spring:
  application:
    name: userserver
  datasource:
    url: jdbc:mysql:///user?serverTimezone=UTC
    username: root
    password: 856724bb
    driver-class-name: com.mysql.cj.jdbc.Driver

#eureka地址
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:11011/eureka/

Insert image description here

④ Add the @EnableEurekaServer annotation to the startup class

Insert image description here

以上是 user 的注册,order 同理!

Insert image description here

5. Write business code

It is required to query the order table, which contains user information.

① Entity class

Insert image description here

Insert image description here

Insert image description here

② Add camel case naming function and entity mapping to the configuration file

#开启驼峰命名及实体映射
mybatis:
  type-aliases-package: com.zxe.orderserver.pojo
  configuration:
    map-underscore-to-camel-case: true
    

③ Write code for data layer, business layer and control layer

Insert image description here
Insert image description here

Insert image description here

Insert image description here

Insert image description here

6. Service pull

Service pulling is to obtain the service list based on the service name, and then perform load balancing on the service list.

① Register RestTemplate in the startup class of order-service

Insert image description here

@LoadBalanced 注解用来做负载均衡!

② Write the OrderService code. To call user, order naturally needs to use the access path of the user interface. In the path here, we use the service name instead of localhost.

@Service
public class OrderService {
    
    

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RestTemplate restTemplate;

    public Order findById(Integer id) {
    
    
        Order order = orderMapper.find(id);
        String url = "http://userserver/user/" + order.getUserId();
        User user = restTemplate.getForObject(url, User.class);
        order.setUser(user);
        return order;
    }
}

③ Operation results

Insert image description here

Guess you like

Origin blog.csdn.net/m0_52861684/article/details/134341738