[] Spring Cloud Spring Cloud using summary

Project Summary

Project Environmental Information

IDEA ultimate 2018.3.2
springboot 2.1.7.RELEASE
springCloud Greenwich.SR2
Enter a description of the picture here

Eureka Introduction

Based netflix eureka secondary package made
of two components:

  • Eureka Server registry
  • Eureka Client service registers

Build Eureka Server

1, the configuration of Eureka application.yml

eureka:
   client:
      serviceUrl:
          defaultZone: http://localhost:8761/eureka/
      #默认为true,是否向自己注册自己
      register-with-eureka: false 
   #关闭Eureka自我保护(生产环境要设置为true,测试环境设置为false)
   server:
     enable-self-preservation: false 
#配置服务实例名
spring:
   application:
      name: spring-cloud-eureka
#配置服务实例端口
server:
   port: 8761

Note: If a read error application.yml file error checking Settings-> File Encodings, all set. 8-UTF
2, arranged Eureka pom.xml

<?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">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.practice</groupId>
    <artifactId>eureka</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>eureka</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR2</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

3, Eureka inlet class

package com.practice.eureka;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {

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

}

4, Eureka High Availability

设置启动端口在VM options设置启动端口
-Dserver.port=8761

Enter a description of the picture here
May be configured as a plurality of start, each register
Enter a description of the picture here

Eureka Server heartbeat detection, health checks, load balancing and other functions.

You can start multiple Eureka Server, registered with each other (start multiple Eureka Server by modifying the ports, modify registry address for each other to achieve mutual registration)
such as, Eureka Server1 and Eureka Server2 launched
after this Eureka Client registration to which a Eureka Server (such as Server1), will be synchronized to another Eureka Server.
If Eureka Server1 hung up, another Eureka Server2 still available, and can be found in the client.

But if you restart Eureka Client, will be found due to the Server1 has stopped, and you can not properly registered, it can not synchronize to Server2

为了确保高可用,可以将Client同时注册到所有的Eureka上

-注册中心地址配置
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka,http://localhost:8762/eureka

如果超过两台以上的Eureka Server,为保证高可用,则可以设置其两两注册,同时将Client同时注册到所有Eureka Server上。

注册发现

1、客户端入口类
添加EnableDiscoveryClient,提供eureka客户端

package com.practice.client;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class ClientApplication {

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

}

2、Client新建application.yml

eureka:
   client:
      serviceUrl:
         defaultZone: http://localhost:8761/eureka/
    #页面跳转后台端口前名称
#   instance:
#      hostname: product 
#客户端实例在注册中心的名称
spring:
   application:
      name: product
   # mysql数据库连接信息
   datasource:
     driver-class-name: com.mysql.jdbc.Driver
     username: root
     password: 123456
     url: jdbc:mysql://127.0.0.1:3306/springcloud_sell?characterEncoding=utf-8&useSSL=false
   # 打开jpa日志,在控制台打印
   jpa:
     show-sql: true
env: 
   dev

3、Client新建pom.xml

<?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">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.practice</groupId>
    <artifactId>client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>client</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR2</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

4、客户端书写中间实体(*)
下面的JsonProperty中的value是序列化后的名称,定义的名称是为了更好的理解属性

@Data
public class ProductVO {

    /**
     * 此处需要返回给前端name,但是表示的是类目名称,所以添加JsonProperty进行标识
     */
    @JsonProperty("name")
    private String categoryName;

    @JsonProperty("type")
    private Integer categoryType;

    @JsonProperty("foods")
    List<ProductInfoVO> productInfoVOList;
}

Ribbon实现负载均衡

1、了解Ribbon

Eureka属于客户端发现,客户端会向服务器拉取可用的服务器信息,根据负载均衡服务,命中那台服务器发送请求,整个过程都是在客户端完成,并不需要服务器的参与。

Ribbon是netflix ribbon实现的,通过springcloud的封装,轻松的面向服务的rest的模板请求,自动的转换为客户端服务调用。

RestTemplate/zuul/Feign都使用到了Ribbon

SpringCloud在结合Ribbon的负载均衡实践中,封装增加了HTTPClient和OKHttpClient 两种请求端实现,默认使用了Ribbon对Eureka的客户端发现的负载均衡client

2、Ribbon的工作原理

轮寻RoundRobinRule、随机连接RandomRule

Ribbon实现软负载均衡核心有三点

(1)服务发现:依据实例名称,把该实例下所有的实例都找出来

(2)服务选择规则:依据规则从多个规则中选择有效的服务

(3)服务监听:检测失效的服务,做到高效剔除

Ribbon主要组件

serverList (获取所有的可用服务列表)----> ServerListFilter(过滤掉一部分地址) -----> IRule从剩下的地址中选择一个实例,作为目标结果。

HTTP service invocation RestTemplate operations and simple comparison Feign

RestTemplate used in three ways

Detailed restTemplate operation https://blog.csdn.net/itguangit/article/details/78825505

1: Direct use RestTemplate, a bad path fixing modifications
RestTemplate access paths for relatively fixed, if online deployment, not modified; or to launch multiple instances of bad calls and capture

RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://localhost:9001/msg", String.class);
log.info("response{}",response);
return response;

Second way: Using LoadBalancerClient get url through the application name, then use restTemplate
injection LoaderBalancerClient, access to services performed by the service name and port number of ip

 @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/getProductMsg")
    public String getProductMsg(){

        // 方式二:(利用LoadBalancerClient通过应用名获取url,然后在使用restTemplate)
        RestTemplate restTemplate = new RestTemplate();
        ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");
        String url = String.format("http://%s:%s", serviceInstance.getHost(),serviceInstance.getPort() + "/msg");
        String response = restTemplate.getForObject(url, String.class);

        log.info("response{}",response);
        return response;
    }

Three ways: by instantiating restTemplate LoadBalanced

@Component
public class RestTemplateConfig {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

Accessed through the instance name, randomly assigned to a service

String response = restTemplate.getForObject("http://PRODUCT/msg", String.class);

Feign communicate

  • Declarative Rest client (pseudo-RPC)
  • Using interface-based annotation

The first step: introducing rely pom.xml

<!--应用间通信-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>

Step two: add annotations EnableFeignClient

The third step: the service information is invoked by a statement @FeignClient

@FeignClient(value = "product", fallback = ProductClientFallbackImpl.class )
public interface ProductClient {

    /**
     * 获取产品端的信息
     *
     * @return
     */
    @GetMapping("/msg")
    String getProductMsg();
}

Fallback processing information by abnormal

@Component
@Slf4j
public class ProductClientFallbackImpl implements ProductClient {
    /**
     * 获取产品端的信息
     *
     * @return
     */
    @Override
    public String getProductMsg() {
        log.info("返回消息接口出现问题");
        return null;
    }
}

Reference:
springcloud study notes micro-channel ordering system
differences and dependencies of dependencyManagement

Guess you like

Origin www.cnblogs.com/z00377750/p/11387111.html