第一章-xxx概述

1什么是xxx

2注册中心

1-eureka

eureka包含了ribbon

1先写pom

2再写启动类

3最后写Yml

4localhost:端口号测试

1先写pom

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?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>

  <groupId>org.example</groupId>
  <artifactId>cloud_eureka8600</artifactId>
  <version>1.0-SNAPSHOT</version>

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

  <name>cloud_eureka8600</name>
  <!-- FIXME change it to the project's website -->

  <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>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

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

  </dependencies>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>Finchley.RELEASE</version>
        <scope>import</scope>
        <type>pom</type>
      </dependency>
    </dependencies>
  </dependencyManagement>

</project>

2再写启动类

1
2
3
4
5
6
7
8
9
@SpringBootApplication
@EnableEurekaServer
public class Eureka8600
{
    public static void main( String[] args )
    {
        SpringApplication.run(Eureka8600.class,args);
    }
}

3最后写Yml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
spring:
  application:
    name: eureka-server

server:
  port: 8600

eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false  #向注册中心注册自己 默认true
    fetch-registry: false  #抓取服务,默认true

4localhost:端口号 进行测试

2-consul

nConsul是一个分布式服务注册与发现,用于跨任何运行时平台和公共或私有云连接、保护和配置服务。它内置了服务注册与发现框 架、分布一致性协议实现、健康检查、Key/Value 存储、多数据中心方案。它是GO语言写。

image-20200729203144617

1、当 Producer 启动的时候,会向 Consul 发送一个 post 请求,告诉 Consul 自己的 IP 和 Port

2、Consul 接收到 Producer 的注册后,每隔10s(默认)会向 Producer 发送一个健康检查的请求,检验Producer是否健康

3、当 Consumer 发送 GET 方式请求 /api/address 到 Producer 时,会先从 Consul 中拿到一个存储服务 IP 和 Port 的临时表,从表中拿到 Producer 的 IP 和 Port 后再发送 GET 方式请求 /api/address

4、该临时表每隔10s会更新,只包含有通过了健康检查的 Producer

使用

下载https://www.consul.io/

到cmd运行consul agent -dev,也可以写一个Bat运行

默认端口号为:localhost:8500

服务提供者

1pom 2yml 3启动 4业务

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?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>

 <groupId>org.example</groupId>
 <artifactId>cloud_consul_provide8610</artifactId>
 <version>1.0-SNAPSHOT</version>

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

 <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>
 </properties>

 <dependencies>
   <!-- consul需要3个包 -->
     <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-consul-config</artifactId>
     </dependency>

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

     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-actuator</artifactId>
     </dependency>
    <!-- consul需要的3个包 over -->
   <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>Finchley.RELEASE</version>
             <scope>import</scope>
             <type>pom</type>
         </dependency>
     </dependencies>
 </dependencyManagement>
</project>

2yml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
server:
port: 8610
**自身服务的名称 注册中心的配置**
spring:
application:
 name: consul-provider

cloud:
 consul:
   discovery:
     service-name: consul-provider  # 服务提供者名称
   host: localhost                  # consul 所在服务地址
   port: 8500

3启动

@EnableDiscoveryClient可以不使用,在consul里会自动发现服务

1
2
3
4
5
6
7
8
@SpringBootApplication
@EnableDiscoveryClient
public class ConsulProvide8610 {
 public static void main(String[] args) {

     SpringApplication.run(ConsulProvide8610.class, args);
 }
}

4业务

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
@RestController
public class HelloController {
 @Value("${server.port}")
 String port;

 @GetMapping(value = "test")
 public String test(){

     return port+"提供的hello spring cloud!";
 }

 @GetMapping(value = "nice")
 public String nice(){

     return port+"提供的nice to meet you!";
 }
}

消费者

1pom 2yml 3启动 4业务

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 <parent>
        <groupId>org.springframework.boot</groupId>
        <version>2.0.5.RELEASE</version>
        <artifactId>spring-boot-starter-parent</artifactId>
    </parent>

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

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

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

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.RELEASE</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>

2yml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
server:
  port: 8611
服务消费者 设置不去consul注册**
spring:
  application:
    name: consul-customer

  cloud:
    consul:
      discovery:
        register: false

3启动类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ConsulConsumer8611 {

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

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

4业务调用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//写接口
@Component
@FeignClient("consul-provider")
public interface MyService {
    @GetMapping("test")
    public String t1();
    @GetMapping("nice")
    public String t2();
}

//========
//调用
@RestController
public class ConsumerController {
    @Autowired
    private MyService myService;

    @GetMapping("consulHello")
    public String consulHello(){
      return   myService.t1();
    }

    @GetMapping("consulNice")
    public String consulNice(){
        return   myService.t1();
    }

}

3远程调用

1-ribbon远程调用

需要一个服务提供者 需要一个服务消费者

1加入jar包

2编写Yml

3编写启动类

4编写业务

服务提供者

1加入jia

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?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>

  <groupId>org.example</groupId>
  <artifactId>cloud_ribbon_provide8601</artifactId>
  <version>1.0-SNAPSHOT</version>

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

  <name>cloud_ribbon_provide8601</name>

  <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>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
      <version>2.0.0.RELEASE</version>
    </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>Finchley.RELEASE</version>
        <scope>import</scope>
        <type>pom</type>
      </dependency>
    </dependencies>
  </dependencyManagement>
</project>

2编写yml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12

spring:
  application:
    name: goods     #去注册中心 注册的服务名

server:
  port: 8601

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8600/eureka/   #服务器地址

3编写启动类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
@SpringBootApplication
@EnableDiscoveryClient  //表示提供向注册中心注册服务
public class RibbonProvide8601
{
    public static void main( String[] args )
    {

        SpringApplication.run(RibbonProvide8601.class,args);
    }
}

4编写业务 对外提供服务

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
@RestController
public class GoodsController {

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

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

        return port+"端口提供的服务";
    }
}

服务消费者

1加入jar

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?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>

  <groupId>org.example</groupId>
  <artifactId>cloud_ribbon_consumer8602</artifactId>
  <version>1.0-SNAPSHOT</version>

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

  <name>cloud_ribbon_consumer8602</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <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>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
      <version>2.0.0.RELEASE</version>
    </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>Finchley.RELEASE</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

2编写Yml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
spring:
  application:
    name: comsumer

server:
  port: 8602

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8600/eureka/

3启动类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@SpringBootApplication
@EnableDiscoveryClient
public class ribbon_consumer8602
{
    @Bean   //需要再一个SpringBootConfiguration注解,@SpringBootApplication已经包含
    @LoadBalanced  //负载均衡
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

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

4业务调用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
@RestController
public class ConsumerController {
    @Autowired
    RestTemplate restTemplate;

    @GetMapping("consumer")
    public String cm(){
        System.out.printf("8602的端口consumer");
        String url="http://goods/good";
        return restTemplate.getForObject(url,String.class);
    }
    
}

就会发现8602调用了 8601的端口

2-feign远程调用

1加入jar包

2编写Yml

3编写启动类

4编写业务

1加入jar包

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
 <parent>
        <groupId>org.springframework.boot</groupId>
        <version>2.0.5.RELEASE</version>
        <artifactId>spring-boot-starter-parent</artifactId>
    </parent>

    <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>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.RELEASE</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>

2编写Yml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14

spring:
  application:
    name: feignConsumer

server:
  port: 8604

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8600/eureka/


3编写启动类

1
2
3
4
5
6
7
8
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients  //开启feign客户端
public class CloudFeignConsumer8604 {
    public static void main(String[] args) {
        SpringApplication.run(CloudFeignConsumer8604.class,args);
    }
}

4编写业务

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
//先写一个接口
@Component 
@FeignClient("goods")//注册中的的服务程序
public interface MyService {

    @GetMapping("good")//注册中心的业务controller路径
    public String cm();
}

//==========  controller调用
@RestController
public class FeignController {
    @Autowired
    MyService myService;
    @GetMapping("feignConsumer")
    public String t1(){
        System.out.println("feignController测试了");
        return myService.cm();
    }
}

4服务熔断

1-Hystrix

https://www.cnblogs.com/haha12/archive/2019/10/17/11690489.html


在feign远程调用中使用

1加入jar包

2编写Yml

3编写启动类

4编写业务

1加入jar包

1
2
3
4
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

2编写Yml

feign: hystrix: # feign熔断器开关 enabled: true

3编写启动类

@EnableHystrix //在启动类上添加@EnableHystrix注解开启Hystrix的熔断器功能。

4编写业务

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
//在调用远程方法的地方
//加入fallback = MyServiceClass.class)
//这个类为实现本接口的类
@Component
@FeignClient(name = "goods",fallback = MyServiceClass.class)
public interface MyService {

    @GetMapping("good")
    public String cm();
}

//实现本接口的类
@Component
public class MyServiceClass implements MyService{
    @Override
    public String cm() {
        return "8604服务熔断的方法";
    }
}


在ribbon远程调用

1加入jar包

2编写Yml

3编写启动类

4编写业务

差异的步骤4编写代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
@HystrixCommand(fallbackMethod = "getDefaultUser")
@GetMapping("consumer")
public String cm(){
    System.out.printf("8602的端口consumer");
    String url="http://goods/good";
    return restTemplate.getForObject(url,String.class);
}

public String getDefaultUser(){
    return "8602熔断的返回结果";
}

5路由网关

1zuul

作用

  • 统一入口:未全部为服务提供一个唯一的入口,网关起到外部和内部隔离的作用,保障了后台服务的安全性。
  • 鉴权校验:识别每个请求的权限,拒绝不符合要求的请求。
  • 动态路由:动态的将请求路由到不同的后端集群中。
  • 减少客户端与服务端的耦合:服务可以独立发展,通过网关层来做映射。

两大功能:路由转发、请求过滤

1加入jar 2编写yml 3编写启动 4也业务

1加入jar

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>2.0.6.RELEASE</version>
</parent>

 <dependencyManagement>
     <dependencies>
         <dependency>
             <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-dependencies</artifactId>
             <version>Finchley.RELEASE</version>
             <scope>import</scope>
             <type>pom</type>
         </dependency>
     </dependencies>
 </dependencyManagement>

<dependencies>
  <!--consul注册中心的三个Jar-->
  <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-consul-config</artifactId>
  </dependency>

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

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
  </dependency>
<!--zuul网关-->
  <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
  </dependency>
</dependencies>

2编写yml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
服务端口号**
server:
port: 8620

服务名称**
spring:
application:
 name: cloud_zuul

cloud:
consul:
 discovery:
   service-name: consul-provider  # 服务提供者名称
 host: localhost                  # consul 所在服务地址
 port: 8500

网关设置**
zuul:
  routes:
    consumer-provider8610:
      path: /provider8610/**
      serviceId: consul-provider
    consul-provider8621:
      path: /provider8621/**
      serviceId: consul-provider8621
  #让cookie不失效
  sensitive-headers:
  #设置超时时间
  host:
    connect-timeout-millis: 6000  

3编写启动类

1
2
3
@SpringBootApplication
@EnableZuulProxy //开启路由网关代理
@EnableDiscoveryClient //开启注册中心客户端

4filter过滤业务

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package com.lx.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    RedisTemplate redisTemplate;

    //设置过滤的时机 pre前置过滤 post后置过滤  error出现错误时过滤
    @Override
    public String filterType() {
        return "pre";
    }

    //多个过滤器 设置过滤器优先级 值越小,优先级越大
    @Override
    public int filterOrder() {
        return 1;
    }

    //当前是否启动过滤 true启动/false不过滤
    @Override
    public boolean shouldFilter() {
        //获得请求上下文
        RequestContext requestContext=RequestContext.getCurrentContext();

        //获取请求对象
        HttpServletRequest request = requestContext.getRequest();

        //若请求路径为登录时,就放行
        String requestURI = request.getRequestURI();
        System.out.println("zuul获得的shouldFilter方法 请求路径为:"+requestURI);
        //获取的是localhost:8080后的东西
        if("/provider8621/checkAccount".equalsIgnoreCase(requestURI)){
            return false;
        }

        return true;
    }

    //执行过滤的方法
    @Override
    public Object run() throws ZuulException {
        //若含有token 且redis含有tooken值就放行
        System.out.println("zuul的LoginFilter run方法");

        //看是否含有token
        RequestContext requestContex=RequestContext.getCurrentContext();
        HttpServletRequest request = requestContex.getRequest();

        //String token = request.getParameter("token");
        String token=null;
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            if(cookies[i].getName().equals("token")){
               token=cookies[i].getValue();
                System.out.println("找到了token "+token);
                break;
            }
        }
        if(token==null || "".equals(token)){
            System.out.println("没有token不放行");
            requestContex.setSendZuulResponse(false);//是否由zuul进行转发

            requestContex.setResponseStatusCode(666);
            try {
                requestContex.getResponse().getWriter().write("You need the token");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        //找到了token还需要查看redis中是否含有
        Object o =  redisTemplate.opsForValue().get(token);
        if(o!=null){
            String name=(String)o;
            System.out.println("redis找到了token 其name为"+name);
            requestContex.setSendZuulResponse(true);//是否由zuul进行转发
        }else{
            requestContex.setSendZuulResponse(false);//是否由zuul进行转发
            requestContex.setResponseStatusCode(996);
        }
        return null;
    }
}

2gateway

两大功能:路由转发、请求过滤

1加入jar 2编写yml 3编写启动 4也业务

1jar

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?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>

    <groupId>org.example</groupId>
    <artifactId>cloud_gateway8630</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.RELEASE</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!--gateway网关-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-gateway-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

        <!--consul注册中心的三个Jar-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-config</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!--整合redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!--热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
</project>

2yml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
服务端口号**
server:
  port: 8630

服务名称**
spring:
  application:
    name: cloud_gateway8630
  cloud:
    consul:
      discovery:
        service-name: cloud_gateway  # 服务提供者名称
      host: localhost                  # consul 所在服务地址
      port: 8500
    gateway:
      discovery:
        #enabled: true 表示gateway开启服务注册和发现功能,
        #并且spring cloud gateway自动根据服务发现为每一个服务创建了一个router,这个router将以服务名开头的请求路径转发到对应的服务
        locator:
          enabled: true
          lower-case-service-id: true #表示将请求路径的服务名配置改成小写  因为服务注册的时候,向注册中心注册时将服务名转成大写的了
      routes:
        - id: consul-provider8610
          uri: lb://consul-provider8610
          predicates:
            - Path=/provider8610/**

        - id: consul-provider8621
          uri: lb://consul-provider8621
          predicates:
            - Path=/account/**   #这里表示拦截的controller路径account

整合redis**
jedis :
  pool :
    host : 127.0.0.1
    port : 6379
    config :
      maxTotal: 100  #最大连接
      maxIdle: 10   #最大空闲
      maxWaitMillis : 100000  

3启动类``

1
2
@SpringBootApplication
@EnableDiscoveryClient

4业务类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.lx.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class MyGlobalFilter implements GlobalFilter {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求路径 如果请求路径是checkAccount的话就放行,
      
				////获取请求路径 拦截路径为:/account/checkAccount
        RequestPath path = exchange.getRequest().getPath();
        if("/account/checkAccount".equals(path.value())){
            return chain.filter(exchange);//放行
        }else {
            //若不是这个路径就要查看是否有token
            MultiValueMap<String, HttpCookie> cookies = exchange.getRequest().getCookies();
            HttpCookie token = cookies.getFirst("token");

            //没有token就进行拦截
            if(token==null) {
                System.out.println("没有token  不放行");
                return exchange.getResponse().setComplete();//拦截
            }else {
                System.out.println("含有token redis中进行验证");
                Object o = redisTemplate.opsForValue().get(token.getValue());
                if(o==null){
                    System.out.println("redis没有token 不放行");
                    exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);//设置返回信息
                    return exchange.getResponse().setComplete();
                }else {
                    System.out.println("redis有token 放行");
                    return chain.filter(exchange);//放行
                }
            }
        }
    }
}

第二章-服务管理

1配置管理

1-CloudConfig

需要有服务端口 和客户端

服务端

1加入jar

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?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>

    <groupId>org.example</groupId>
    <artifactId>cloud_config-server8640</artifactId>
    <version>1.0-SNAPSHOT</version>

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

<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>
</properties>

<dependencies>
    <!-- consul需要3个包 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-consul-config</artifactId>
    </dependency>

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <!-- consul需要的3个包 over -->

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

    <!-- config ======加入这个 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-server</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Finchley.RELEASE</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>
</project>

2编写Yml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
server:
  port: 8640
spring:
  application:
    name: configServer8640
  cloud:
    config:
      server:
        git:
          uri: https://github.com/13277112287/CloudConfig  #git仓储的地址
          search-paths: /file      #文件夹的名称
          username:                #若是私有仓库 需要账号密码
          password:
      label: master               #分支
    consul:
      host: localhost                  # consul 所在服务地址
      port: 8500

3启动类

1
2
3
@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigServer

4github上的

image-20200731231017758

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
server:
  port: 8641
**自身服务的名称 注册中心的配置**
spring:
  #application:          在bootstrap.yml中已经配置,config是根据bootstrap的name和profile来查找配置
   #name: configClient8641

  cloud:
    consul:
      discovery:
        service-name: configClient8641  # 服务提供者名称
      host: localhost                  # consul 所在服务地址
      port: 8500

客户端

1jar 把服务端的配置换一个就好了

1
2
3
4
5
<!-- config -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-client</artifactId>
        </dependency>

2启动类

1
2
@SpringBootApplication
@EnableDiscoveryClient

3bootstrap.yml

1
2
3
4
5
6
7
8
9
spring:
  application:
    name: configClient8641
  cloud:
    config:
      discovery:
        enabled: true
        service-id: configServer8640 #configServer 配置服务中心的应用名
      profile: dev

4业务类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.lx.controller;

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

@RestController
//@RequestMapping(value = "provider8610")
public class HelloController {


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

    @GetMapping(value = "test")
    public String test(){

        return port+"提供的hello spring cloud!TTTTTTT";
    }

    @GetMapping(value = "nice")
    public String nice(){

        return port+"提供的nice to meet you!SSSSSSS";
    }
}