Java springboot integrates spring cloud

Time:2021-12-3

Spring boot integrates spring cloud


1. Spring cloud features

Spring cloud focuses on providing a good out of the box experience for typical use cases and extension mechanisms to cover other situations:

  • Distributed / versioned configuration

  • Eureka service registration and discovery

  • Routing zuul

  • Service to service call

  • Load balancing ribbon

  • Circuit breaker hystrix

  • Distributed messaging

2. Three indicators cap of distributed system

Before introducing the registry used by spring cloud by default, first introduce the three indicators of the distributed system, namely:

  • Consistency: consistency. In a distributed system, after the update operation is successfully executed, all users’ read operations must return the latest value; Client writes and server synchronizes to the whole system;

  • AvailabilityAvailability: as long as the user’s request is received, the server must respond within a certain time, and the response result can be success or failure;

  • Partition tolerance: partition fault tolerance, that is, interval communication may fail, and external services are still provided in case of network interruption and message loss; Generally, it cannot be avoided. It can be considered that P in cap is always true

Cap law says that in a distributed computer system, the three guarantees of consistency C, availability A and partition fault tolerance P cannot be met at the same time, and at most two are met:

  1. Abandon p

In order to avoid the problem of partition fault tolerance, one approach is to put all transaction related data on one server. Although it can not guarantee that 100% of the system will not make mistakes, it will not encounter the negative effects brought by partition. This approach will seriously affect the scalability of the system.

  1. Abandon a

Give up availability. Once a partition fault tolerance fault occurs, the affected server needs to wait for a certain time, so the system will not be able to provide external services during the waiting period.

  1. Abandon C

Abandoning consistency here does not mean abandoning the consistency of data completely, but abandoning the strong consistency of data and retaining the final consistency of data. Take online shopping as an example. For goods with only one inventory, if two orders are received at the same time, the later orders will be told that the goods are sold out.

Some cap theories in this paper are extracted from:https://www.cnblogs.com/hxsyl/p/4381980.html

3. Eureka

Basic introduction

Eureka is a rest based service officially recommended by spring cloud for service registration and discovery

Springboot implements the integration of Netflix OSS. One of the reasons for using Eureka is that it can take advantage of other components of spring cloud Netflix: intelligent routing (zuul), client load balancing (ribbon), etc

Basic composition

Eureka consists of multiple instances (service instances), which are divided intoEureka ServerandEureka Client

Eureka client can be subdivided into service provider and service consumer

  • Eureka server: server, which provides service registration and discovery;

  • Eureka client: client

    • Service provider: a service provider that registers its services with Eureka so that consumers can find them
    • Service consumer: a service consumer who obtains a list of registered services from Eureka to consume services

Eureka and zookeeper

1) From the perspective of cap theory

Zookeeper:ZK guaranteed CP, strong consistency is highlighted, but the service availability of each access cannot be guaranteed. For example, ZK will have such a situation: when the master node loses contact with other nodes due to network failure, the remaining nodes will conduct leader election again. During ZK leader election, the whole ZK cluster is unavailable, which leads to the paralysis of registration services during the election. In the cloud deployment environment, ZK clusters are likely to lose the master node due to network problems. Although the service will eventually be restored, the long-term unavailability of registration caused by the long election time is intolerable.

Eureka:Eureka guaranteed AP, Eureka gives priority to ensuring availability at the time of design. For the nodes in Eureka, each node is equal. If several nodes hang up, it will not affect the work of normal nodes. The remaining nodes can still provide registration and query services. However, Eureka does not guarantee strong consistency, that is, the information found may not be up-to-date. In addition, Eureka has a self-protection mechanism. If more than 85% of the nodes do not have a normal heartbeat within 15 minutes, Eureka will think that there is a network failure in the client and registry, but it will ensure that the current node is still available and will not paralyze the whole registration service like ZK.

2) From the perspective of node division of labor

Zookeeper: nodes in ZK cluster are divided into three categories and undertake different tasks

  • Leader: the unique dispatcher and processor of transaction requests (except query requests)
  • Follower: handle non transaction requests and participate in leader election voting
  • Observer: handles non transaction requests, but does not participate in leader election voting

Eureka: in Eureka cluster, each node is equal and plays the same role. They perceive each other’s existence by registering with each other. When messages are registered, they will be synchronized to other nodes in the cluster

Chinese documents:https://www.springcloud.cc/spring-cloud-greenwich.html#_spring_cloud_netflix

4. SpringCloud Demo

Demo overall structure(parent child project)

  • API: bean, dto, POJO and service interface

  • Controller: service consumer, front-end interaction

  • Provider: service provider, service implementation

  • Registry: Service Registry

4.1 registry

1)pom.xml

The key point isImport Eureka server dependencyAnd spring cloud dependencies

org.springframework.cloud
            spring-cloud-starter-netflix-eureka-server
            2.2.5.RELEASE
        

    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                Hoxton.SR6
                pom
                import

2)application.properties

Configure Eureka server

spring.application.name=SpringCloudDemoRegistry

#Server port, I like it
server.port=8888

#Eureka server service URL and default zone must end with Eureka
eureka.client.service-url.defaultZone= http://127.0.0.1:8888/eureka/

#Eureka's self-protection mechanism. False is recommended in k8s environment
eureka.server.enable-self-preservation=false

#False means that my client is the registration center. My function is to maintain service instances without obtaining registered service information from the server
eureka.client.fetch-registry=false

#False means that you do not register yourself with Eureka server
eureka.client.register-with-eureka=false

3)EurekaregistryApplication

use@EnableEurekaServerActivate the relevant configuration so that the registry module acts as the registry server

@Enableeurekaserver // declare as the registry server
@SpringBootApplication
public class EurekaregistryApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaregistryApplication.class, args);
    }
}

4.2 api

1)entity

The entity class takes department and user information as an example. Because Lombok pointless code is used in the demonstration, it is used to implement the basic crud

Department.class

@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Department {
    private Long id;
    private Integer dId;
    private String dName;
    private Date updateTime;
}

UserInfo.class

@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class UserInfo {
    private Long id;
    private Integer uId;
    private Integer dId;
    private String uName;
    private String uPhone;
    @Email (message = "illegal message format") // validator format verification
    private String uEmail;
    private String uAddress;
    private Date updateTime;
    private Department department;
}

2)UserService

Userservice is a service interface, which declares the methods to be provided and consumed, and writes several simple queries

public interface UserService {

    /**
     *Judge whether the user exists. If 0 is nonexistent, it exists if the return value is equal to uid
     * @param uId
     * @return
     */
    Integer userExist(Integer uId);

    /**
     *Obtain user's basic personal information
     * @param uId
     * @return
     */
    UserInfo getUserInfo(Integer uId);

    /**
     *Get user personal details
     * @param uId
     * @return
     */
    UserInfo getUserDetailsInfo(Integer uId);
}

4.3 provider

1)pom.xml

The key point isIntroducing Eureka client dependenciesOpenfeign dependencySpring cloud dependency

org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        

        
            org.springframework.cloud
            spring-cloud-starter-openfeign
        



        
            
                org.springframework.cloud
                spring-cloud-dependencies
                Hoxton.SR6
                pom
                import

2)application.properties

Configure Eureka, mybatis and datasource data sources

spring.application.name=SpringCloudDemoProvider

#Server port
server.port=9999

#Eureka service URL
eureka.client.service-url.defaultZone= http://127.0.0.1:8888/eureka/
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true

# Mybatis
mybatis.mapper-locations= classpath:com.maziyao.provider.mapper/*.xml
mybatis.type-aliases-package= com.maziyao.common.entity

#Datasource data source configuration
spring.datasource.type=com.zaxxer.hikari.HikariDataSource

# DataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/boot-demo?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

3)EurekaproviderApplication

Provider startup class use@EnableEurekaClientDeclared as eurekaclient client as serviceprovider

@EnableEurekaClient
@SpringBootApplication
@EnableAspectJAutoProxy
@MapperScan("com.maziyao.provider.mapper")
@ComponentScan(basePackages = {
        "com.maziyao.provider.rest",
        "com.maziyao.provider.redis",
        "com.maziyao.provider.service",
        "com.maziyao.provider.config"
})
public class EurekaproviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaproviderApplication.class, args);
    }
}

4)service

Userserviceimpl is the implementation class of userservice interface,@ServiceFor dimensioningBusiness layerassembly

Automatically inject the mapper interface of the mapper layer and call it. The mapper SQL statement is omitted below, which is very simple

It should be noted that forData access layerComponent mapper, using@RepositoryAnnotate

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Integer userExist(Integer uId) {
        return userMapper.userExist(uId);
    }

    @Override
    public UserInfo getUserInfo(Integer uId) {
        return userMapper.getUserInfo(uId);
    }

    @Override
    public UserInfo getUserDetailsInfo(Integer uId) {
        return userMapper.getUserDetailsInfo(uId);
    }
}

5)rest

The focus is on the userserver under the rest package,You should know that Eureka is a rest based service

use@RestControllerAnnotate and declare as userserver. This is the spring boot annotation for annotationControl layerassembly

@RestController("userServer")
public class UserServer {

    public static final Logger logger = LoggerFactory.getLogger(UserServer.class);

    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping(value = "/exist",method = RequestMethod.GET)
    public Integer existUserByUid(@RequestParam("uId")Integer uId){
        return userService.userExist(uId);
    }

    @ResponseBody
    @RequestMapping(value = "/userInfo",method = RequestMethod.GET)
    public UserInfo getUserInfo(@RequestParam("uId")Integer uId){
        return userService.getUserInfo(uId);
    }

    @ResponseBody
    @RequestMapping(value="/userDetailsInfo",method = RequestMethod.GET)
    public UserInfo getUserDetailsInfo(@RequestParam("uId")Integer uId){
        return userService.getUserDetailsInfo(uId);
    }
}

4.4 consumer

1)pom.xml

You also need to import in pom.xml of controllerEurekaClientFor both provider and controller, it is client

org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
            2.2.5.RELEASE
        

        
            org.springframework.cloud
            spring-cloud-starter-openfeign
            2.2.5.RELEASE

2)application.properties

Configure Eureka related information in application.properties

spring.application.name=springCloudDemoController

#Server port
server.port=8899

#Registry URL
eureka.client.service-url.defaultZone= http://127.0.0.1:8888/eureka/
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true

3)EurekacontrollerApplication

Consistent with the startup class of provider, the startup class is declared asEureka’s client

And use@EnableFeignClientsOpen feign, a declarative web service client

@EnableEurekaClient
@EnableFeignClients
@SpringBootApplication
@EnableAspectJAutoProxy
@ComponentScan({
        "com.maziyao.controller.config",
        "com.maziyao.controller.controller",
        "com.maziyao.controller.rest"
})
public class EurekacontrollerApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekacontrollerApplication.class, args);
    }

}

4)rest

Controller is the front-end interaction layer, that is, the control layer. Here, userclient declares to call the method

use@FeignClientDeclare the spring.application.name configured by the service provider in application.properties

And bind the @ restcontroller of the userserver class under the rest package corresponding to the service provider(“userServer“)

@FeignClient(name = "springCloudDemoProvider",contextId = "userServer")
public interface UserClient {

    @ResponseBody
    @RequestMapping(value = "/exist",method = RequestMethod.GET)
    public Integer existUserByUid(@RequestParam("uId")Integer uId);

    @ResponseBody
    @RequestMapping(value = "/userInfo",method = RequestMethod.GET)
    public UserInfo getUserInfo(@RequestParam("uId")Integer uId);

    @ResponseBody
    @RequestMapping(value="/userDetailsInfo",method = RequestMethod.GET)
    public UserInfo getUserDetailsInfo(@RequestParam("uId")Integer uId);

}

5)UserController

Control layer, using@RestControllerAnnotate and inject userclient for calling

@RestController
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserClient userClient;

    @ResponseBody
    @RequestMapping(value = "/exist",method = RequestMethod.GET)
    public Integer existUserByUid(@RequestParam("uId") Integer uId){
        return userClient.existUserByUid(uId);
    }

    @ResponseBody
    @RequestMapping(value = "/userInfo",method = RequestMethod.GET)
    public UserInfo getUserInfoByUid(@RequestParam("uId")Integer uId){
        return userClient.getUserInfo(uId);
    }

    @ResponseBody
    @RequestMapping(value = "/userDetailsInfo",method = RequestMethod.GET)
    public UserInfo getUserDetailsInfoByUid(@RequestParam("uId")Integer uId){
        return userClient.getUserDetailsInfo(uId);
    }

}

4.5 postman

be carefulFinally, remember MVN install. You need to run registry first, and then run provider and controller respectively

Start registry:

Start provider:

Start consumer:

result: