Spring cloud system and use

SpringCloud system introduced

Spring Cloud Netflix

  • Netflix Eureka: service management components, including service registration and discovery
  • Netflix Ribbon: balancing client load component service invocation
  • Netflix Hystrix: fault-tolerant management components to achieve a fuse
  • Netflix Feign: Ribbon and Hystrix based declarative, template-based HTTP service call component
  • Netflix Zuul: Gateway component that provides intelligent routing, access filtering,
  • Netflix hystrix-dashboard: a single service monitoring
  • Netflix Turbine: Turbine polymerization is a tool server sends event data stream, for metrics in the case hystrix monitor cluster.
  • Netflix Archaius: Configuration of external components
  • ...

Spring Cloud

  • Spring Cloud Config: configuration management tools to achieve external storage applications configured to support client configuration information is refreshed, the encryption / decryption configuration content.
  • Spring Cloud Bus: Change event or events, message bus for propagating state cluster, and triggering subsequent processing
  • Spring Cloud Security: Based on spring security security toolkit, add security controls for our applications
  • Spring Cloud Consul: Consul encapsulates operation, Consul is a service discovery and configuration tool (similar role and Eureka), can be seamlessly integrated with the container Docker
  • Spring Cloud OAuth2: Certification authentication
  • Spring Cloud Task: provide cloud scheduled task management, task scheduling.
  • Spring Cloud Sleuth: log collection kit, a package Dapper and log-based tracking, and Zipkin and HTrace operation, implemented for a distributed application SpringCloud tracking solution.
  • Spring Cloud for Cloud Foundry: binding agreement to service by Oauth2 CloudFoundry, CloudFoundry is VMware launched an open source PaaS cloud platform.
  • Spring Cloud Cluster: Leadership provide election
  • Spring Cloud Data Flow: large data manipulation tools, as an alternative Spring XD, which is a hybrid model and combines the data flow and batch processing mode data.
  • Spring Cloud Stream: dataflow operations development kit, a package of message transmission and Redis, Rabbit, Kafka like.
  • Spring Cloud Zookeeper: Zookeeper operations toolkit for use zookeeper way of service discovery and configuration management.
  • Spring Cloud Connectors: Cloud facilitate various applications of PaaS is connected to the rear end, such as: database and message broker service.
  • Spring Cloud Starters: Spring Boot-style start-up projects, providing dependency management out of the box for the Spring Cloud.
  • Spring Cloud CLI: Based on Spring Boot CLI, allows you to quickly create command line cloud components.

Eureka registry

Create a spring-cloud project

Building a Maven project: spring-cloud-demo
added to the pom.xml file:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.20.RELEASE</version>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring-cloud.version>Dalston.SR4</spring-cloud.version>
    <spring-boot.version>1.5.20.RELEASE</spring-boot.version>
</properties>

<!--对子模块依赖包的版本统一控制,子模块需要显示引用,子模块也可以重新声明版本-->
<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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring-boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Build a service registry Eureka Service

Add module in spring-cloud-demo project: eureka-server
join rely on pom.xml file:

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

Create a file in the resource directory: application.properties, reads as follows:

################### Eureka服务端配置 ####################
server.port=8761
eureka.instance.hostname=localhost
#不向注册中心注册自己
eureka.client.register-with-eureka=false
#由于注册中心的职责就是维护服务实例,它并不需要去检索服务, 所以也设置为false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/

Creating a startup class: EurekaServerApplication.java, add the following:

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

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {

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

Main method runs EurekaServerApplication class, thus Eureka build complete server
access Eureka server in the browser: http: // localhost: 8761 /

Service registration and discovery: Eureka build service registrants

Add module in spring-cloud-demo project: demo-service
added to rely in pom.xml file:

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

Create a file in the resource directory: application.properties, reads as follows:

########## Eureka客户端配置 ############
server.port=9806
spring.application.name=demo-service
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/

Creating a startup class: DemoServiceApplication.java, add the following:

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

@SpringBootApplication
@EnableDiscoveryClient
public class DemoServiceApplication {

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

Main method runs DemoServiceApplication class, thus Eureka registrants to build complete
access Eureka server in the browser: http: // localhost: 8761 / , find demo-service already registered came

Adding a Controller: PortController.java, add the following:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PortController {

    @Value("${server.port}")
    private String port;

    @RequestMapping("/port")
    public String getPort() {
        return "I am demo-service, I'm from port : " + port;
    }
}

Re-run eureka-client project, the main method EurekaClientApplication class
visit in the browser: http: // localhost: 9806 / port, namely output: I am demo-service, I 'm from port: 9806

Availability registry

Create two profiles in the resource directory eureka-server project
application-peer1.properties

################### Eureka服务端配置 ####################
spring.application.name=eureka-server
server.port=8761
eureka.instance.hostname=peer1
#不向注册中心注册自己
eureka.client.register-with-eureka=false
#由于注册中心的职责就是维护服务实例,它并不需要去检索服务, 所以也设置为false
eureka.client.fetch-registry=false
#高可用配置:注册到其他配置中心
eureka.client.serviceUrl.defaultZone=http://peer2:8762/eureka/

application-peer1.properties

################### Eureka服务端配置 ####################
spring.application.name=eureka-server
server.port=8761
eureka.instance.hostname=peer2
#不向注册中心注册自己
eureka.client.register-with-eureka=false
#由于注册中心的职责就是维护服务实例,它并不需要去检索服务, 所以也设置为false
eureka.client.fetch-registry=false
#高可用配置:注册到其他配置中心
eureka.client.serviceUrl.defaultZone=http://peer1:8761/eureka/

Editing System C: \ Windows \ System32 \ hosts file in the drivers \ etc directory, add the following:

    127.0.0.1       peer1
    127.0.0.1       peer2

The eureka-server project labeled jar package, and then run eureka-server.jar named twice with java -jar and specify a different configuration file:

java -jar eureka-server-0.0.1.jar --spring.profiles.active=peer1
java -jar eureka-server-0.0.1.jar --spring.profiles.active=peer2

Background process

nohup java -jar eureka-server-0.0.1.jar --spring.profiles.active=peer1 >./log/eureka-1.log &

Then visit: http: // localhost: 8761 / , that is found under DS Replicas copy-items: peer2
then visit: http: // localhost: 8762 / , copy the item that is found under DS Replicas Item: peer1
upcoming registration center to register other Sign up centers to achieve the purpose of high availability registry

Service Registration Registration to Eureka cluster configuration:

eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/,http://localhost:8762/eureka/

Ribbon Load Balancing

Service Ribbon consumption and load balancing

Add module in spring-cloud-demo project: demo-service-ribbon
join rely on pom.xml file:

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

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-ribbon</artifactId>
    </dependency>

</dependencies>

Increase application.properties file in the resource directory, add the following:

################## 服务配置 ###############
server.port=9136
spring.application.name=demo-service-ribbon
#注册到注册中心
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/,http://localhost:8762/eureka/

Creating a startup class: ServiceRibbonApplication.java, add the following:

@SpringBootApplication
@EnableDiscoveryClient
public class ServiceRibbonApplication {

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

    @Bean
    @LoadBalanced ////负载均衡配置
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

Add Service category: DemoRibbonService.java, add the following:

@Service
public class DemoRibbonService {

    @Autowired
    RestTemplate restTemplate;

    public String port() {
        return restTemplate.getForObject("http://demo-service/port", String.class);
    }
}

Add Controller class: DemoRibbonController.java, add the following:

@RestController
public class DemoRibbonController {

    @Autowired
    DemoRibbonService demoRibbonService;

    @RequestMapping("hello")
    public String port() {
        return demoRibbonService.port();
    }
}

Were used 9806,9807 port demo-service project built before running
the run demo-service-ribbon project, visit: http: // localhost: 9136 / hello, show the following:
the I AM demo-service, the I'm from Port: 9806
visit again http: // localhost: 9136 / hello, show the following:
the I AM Demo-Service, the I'm from Port: 9807

Description demo-service-ribbon project added @LoadBalanced annotated restTemplate use the Ribbon of load balancing in the demo-service access service

Ribbon load balancing policy configuration

Ribbon load balancing common strategies

  1. RandomRule: a service instance randomly selected from the list of services

  2. RoundRobinRule: in round-robin fashion from the list of services from example

  3. RetryRule: According maxRetryMillis maximum retry retry time parameter to obtain service instances when obtaining a service instance failed

  4. WeightedResponseTimeRule
    The strategy is an extension of RoundRobinRule increase is calculated according to the example of the operation of the weight, and to select examples according to the weight, to achieve a better distribution effect

  5. ClientConfigEnabledRoundRobinRule
    This strategy RoundRobinRule with the same function, its role is to rewrite this strategy may inherit the Choose () method, when the selection policy can not be customized policies can be implemented as an alternative to the parent class

  6. BestAvailableRule
    the policy inherited from ClientConfigEnabledRoundRobinRule, in implementation it into a statistics object LoadBalancerStats load balancer, as well as to meet the requirements of selected examples of instances of the use of statistical information stored in LoadBalancerStats choose a specific algorithm. From the source code, all service instances by traversing the load balancer it maintained, will filter out the failed instance, and find the minimum number of concurrent requests made, so characteristic of this strategy is to select the least busy instance .

  7. PredicateBasedRule
    an abstract strategy, based on Google Guava Collection filter condition interface policy Predicate implemented, the basic realization of the "first filter list, and then select polling"
  8. AvailabilityFilteringRule
    PredicateBasedRule achieved using a linear select, based on the use of eligible, not eligible to find the next, unlike the parent need to traverse all services calculated reselection
  9. ZoneAvoidanceRule
    to be supplemented. .

The configuration procedure

To configure the policy, for example random
method of adding the startup class file ServiceRibbonApplication.java in:

//新增随机策略
@Bean
public IRule ribbonRule() {
    return new RandomRule();    //这里选择随机策略,对应配置文件
}

9806,9807 ports were used to build the demo-service project before you run
and then run the demo-service-ribbon project, visit: http: // localhost: 9136 / hello, you will find several multi-access port is the return of a random
I Demo-Service-AM, from the I'm Port: 9806
the I AM-Demo-Service, the I'm from Port: 9807
the I AM-Demo-Service, the I'm from Port: 9806
the I AM-Demo-Service, the I'm from Port: 9806

Feign declarative service call

Build a service environment

Add module in spring-cloud-demo project: demo-feign-consumer
join rely on pom.xml file:

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

Increase application.properties file in the resource directory, add the following:

################## 服务配置 ###############
server.port=9257
spring.application.name=demo-feign-consumer
#注册到注册中心
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/,http://localhost:8762/eureka/

Creating a startup class: FeignConsumerApplication.java, add the following:

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class FeignConsumerApplication {

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

Add Service category: DemoFeignService.java, add the following:

@FeignClient(value = "demo-service")
public interface DemoFeignService {

    @RequestMapping(value = "/port", method = RequestMethod.GET)
    String hello();
}

Add Controller class: DemoFeignController.java, add the following:

@RestController
public class DemoFeignController {
    @Autowired
    DemoFeignService demoFeignService;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String port() {
        return demoFeignService.hello();
    }
}

They were used demo-service project to build the port before running 9806,9807
run demo-feign-consumer items, visit http: // localhost: 9257 / hello , show the following:
the I AM demo-service, the I'm from Port: 9808
so to achieve a declarative service calls, numerous visits to different ports in order, return, indicating that load balancing has been achieved, the default is to use polling policy

Load Balancing Configuration

Start adding the class file FeignConsumerApplication.java methods:
// new random policy
@Bean
public IRule ribbonRule () {
return new new RandomRule (); // here to choose a random policy, corresponding to the configuration file
}

9806,9807 ports were used to build the demo-service project before you run
and then run the demo-feign-consumer items, visit: http: // localhost: 9257 / hello, you will find several multi-access port is the return of a random
I Demo-Service-AM, from the I'm Port: 9806
the I AM-Demo-Service, the I'm from Port: 9806
the I AM-Demo-Service, the I'm from Port: 9806
the I AM-Demo-Service, the I'm from Port: 9807

Hystrix service fuse

Hystrix is ​​to achieve the role is to achieve the call when the call service is unavailable downgrade, such as return to a friendly tips

feign configuration using hystrix

If you are using feign declarative call, then feign default integrated hystrix, just write feign client fallbalk class and configure it

For example, there is a xxxFeignClient, write fallbalk xxxFeignClient of a class:

@Component
public class xxxFeignClientFallback implements xxxFeignClient {

}

() To add annotations in brackets in xxxFeignClient of @FeignClient:

fallback = xxxFeignClientFallback.class

Add annotations on the boot class call

@EnableFeignClients

If not started xxxFeignClient current packet or a sub-class of the current packet following the packet, and its fallbalk such xxxFeignClient com.xxx.client package classes in the following, based on the caller's start com.xxx.ui package below, the We need to add the following annotation on the class started off with a party:

@ComponentScan(basePackages = {"com.xxx.ui","com.xxx.client"})
@EnableFeignClients(basePackages = {"com.xxx.client"})

Note: Only scan the specified basePackages specified package when the project started after the specified component basePackages

Finally application.properties file caller added to enable feign hystrix configuration:

feign.hystrix.enabled=true

Config Configuration Center

config server

Add module in spring-cloud-demo project: config-server
join rely on pom.xml file:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>

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

Increase application.properties file in the resource directory, add the following:

server.port=8888
spring.application.name=config-server

eureka.client.serviceUrl.defaultZone=http\://localhost\:8761/eureka/
spring.profiles.active=native
spring.cloud.config.server.native.searchLocations=classpath:/properties/

Create a directory under the resource directory: properties, increase the file in the directory: cloud-config-dev.properties, reads as follows

msg=hello, I'm from config-server

Create a SpringBoot project startup class in java catalog: ConfigServer, reads as follows:

/**
 * @CalssName ConfigServer
 * @Description TODO
 */
@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigServer
public class ConfigServer {

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

config end use

Add module in spring-cloud-demo project: config-use
join rely on pom.xml file:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

Increase application.properties file in the resource directory, add the following:

server.port=9802
spring.application.name=config-use
eureka.client.serviceUrl.defaultZone=http\://localhost\:8761/eureka/

spring.cloud.config.discovery.enabled=true
spring.cloud.config.discovery.service-id=config-server
spring.cloud.config.name=cloud-config
spring.cloud.config.profile=${config.profile:dev}

Create a SpringBoot project startup class in java catalog: ConfigUseApplication, reads as follows:

/**
 * @CalssName ConfigUse
 * @Description TODO
 */
@SpringBootApplication
@EnableDiscoveryClient
public class ConfigUseApplication {

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

Creating a Controller: HelloController, reads as follows:

/**
 * @CalssName HelloController
 * @Description TODO
 */
@RestController
public class HelloController {
    @Value("${msg}")
    private String msg;

    @RequestMapping("/msg")
    public String msg() {
        return msg;
    }
}

Eureka in order to start the server, config-server and config-use, browser access: http: // localhost: 9802 / msg, output is as follows:

hello, I'm from config-server

Configure the Center for Applied success

Zuul routing gateway

zuul application side

Add module in spring-cloud-demo project: zuul-app
added to rely on pom.xml file:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>

Increase application.properties file in the resource directory, add the following:

server.port=8080
spring.application.name=zuul-app
eureka.client.serviceUrl.defaultZone=http\://localhost\:8761/eureka/

zuul.routes.zuul-use.path=/api/**
zuul.routes.zuul-use.serviceId=zuul-use

Create a SpringBoot project startup class in java catalog: ZuulApplication, reads as follows:

/**
 * @CalssName ZuulApplication
 * @Description TODO
 */
@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy
public class ZuulApplication {

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

zuul end use

Add module in spring-cloud-demo project: zuul-use
join rely on pom.xml file:

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

Increase application.properties file in the resource directory, add the following:

server.port=8903
spring.application.name=zuul-use
eureka.client.serviceUrl.defaultZone=http\://localhost\:8761/eureka/

Create a SpringBoot project startup class in java catalog: ZuulUseApplication, reads as follows:

/**
 * @CalssName ZuulUseApplication
 * @Description TODO
 */
@SpringBootApplication
@EnableDiscoveryClient
public class ZuulUseApplication {

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

Creating a Controller: HelloController, reads as follows:

/**
 * @CalssName controller
 * @Description TODO
 */
@RestController
public class HelloController {

    @RequestMapping(value = "/hello")
    public String hello(){
        return "hello,I'm from zuul-use...";
    }
}

Eureka in order to start the server, zuul-app and zuul-use, browser access: http: // localhost: 8080 / api / hello, output is as follows:

hello,I'm from zuul-use...

Description zuul successful application

Zuul Advanced Use

Example of use Zuul filter to filter token, for example, in the filter construction TokenFilter zuul-app, as follows:

/**
 * @CalssName TokenFilter
 * @Description Token Zuul过滤器
 * @Author Alyshen
 */
public class TokenFilter extends ZuulFilter {
    private final Logger logger = LoggerFactory.getLogger(TokenFilter.class);

    @Override
    public String filterType() {
        return "pre"; // 可以在请求被路由之前调用
    }

    @Override
    public int filterOrder() {
        return 0; // filter执行顺序,通过数字指定 ,优先级为0,数字越大,优先级越低
    }

    @Override
    public boolean shouldFilter() {
        return true;// 是否执行该过滤器,此处为true,说明需要过滤
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        logger.info("--->>> TokenFilter {},{}", request.getMethod(), request.getRequestURL().toString());

        String token = request.getParameter("token");// 获取请求的参数

        if (StringUtils.isNotBlank(token)) {
            ctx.setSendZuulResponse(true); //对请求进行路由
            ctx.setResponseStatusCode(200);
            ctx.set("isSuccess", true);
            return null;
        } else {
            ctx.setSendZuulResponse(false); //不对其进行路由
            ctx.setResponseStatusCode(400);
            ctx.setResponseBody("token is empty");
            ctx.set("isSuccess", false);
            return null;
        }
    }
}

In the startup class zuul-app added as follows:

@Bean
public TokenFilter tokenFilter() {
    return new TokenFilter();
}

Guess you like

Origin www.cnblogs.com/yhongyin/p/12003983.html