springcloud知识

springcloud

服务提供者

  1. 导入依赖

    <?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">
        <parent>
            <artifactId>springcloud</artifactId>
            <groupId>com.zhao</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>springcloud-provide-dept-8001</artifactId>
    
        <properties>
            <maven.compiler.source>8</maven.compiler.source>
            <maven.compiler.target>8</maven.compiler.target>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>com.zhao</groupId>
                <artifactId>springcloud-api</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
            </dependency>
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-core</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-test</artifactId>
                <version>2.4.4</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
                <version>2.4.4</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jetty</artifactId>
                <version>2.4.3</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <version>2.4.4</version>
            </dependency>
        </dependencies>
    
    </project>
    
  2. 配置yaml

    server:
      port: 8001
    #mybatis的配置
    mybatis:
      type-aliases-package: com/zhao/springcloud/pojo
      mapper-locations: classpath:com/zhao/mapper/*.xml
    #spring的配置
    spring:
      application:
        name: springcloud-provide-dept
      datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        username: root
        password: 123456
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    
  3. 编写实体类、pojo,service和controller

    package com.zhao.springcloud.pojo;
    
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import lombok.experimental.Accessors;
    
    import java.io.Serializable;
    @Data
    @NoArgsConstructor
    @Accessors(chain = true)
    public class dept implements Serializable {
        private long deptno;
        private String dname;
        private String db_source;
    
        public dept(String dname) {
            this.dname = dname;
        }
    }
    
    package com.zhao.springcloud.mapper;
    
    import com.zhao.springcloud.pojo.dept;
    import org.apache.ibatis.annotations.Mapper;
    import org.springframework.stereotype.Repository;
    
    import java.util.List;
    
    @Mapper
    @Repository
    public interface deptmapper {
        public boolean addDept(dept dept);
    
        public dept queryDeptById(long id);
    
        public List<dept> queryAll();
    }
    
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.zhao.springcloud.mapper.deptmapper">
        <select id="queryDeptById" resultType="com.zhao.springcloud.pojo.dept">
            select *
            from dept where deptno = #{deptno};
        </select>
        <select id="queryAll" resultType="com.zhao.springcloud.pojo.dept" parameterType="Long">
            select *
            from dept ;
        </select>
        <insert id="addDept" parameterType="com.zhao.springcloud.pojo.dept">
            insert into dept (dname,db_source)
            values (#{dname},DATABASE());
        </insert>
    </mapper>
    
    package com.zhao.springcloud.service;
    
    import com.zhao.springcloud.pojo.dept;
    
    import java.util.List;
    
    public interface deptService {
        public boolean addDept(dept dept);
    
        public dept queryDeptById(long id);
    
        public List<dept> queryAll();
    }
    
    
    package com.zhao.springcloud.service;
    
    import com.zhao.springcloud.mapper.deptmapper;
    import com.zhao.springcloud.pojo.dept;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    @Service
    public class deptServiceImpl implements deptService{
        @Autowired
         deptmapper deptmapper;
        @Override
        public boolean addDept(dept dept) {
            return deptmapper.addDept(dept);
        }
    
        @Override
        public dept queryDeptById(long id) {
            return deptmapper.queryDeptById(id);
        }
    
        @Override
        public List<dept> queryAll() {
            return deptmapper.queryAll();
        }
    }
    
    package com.zhao.springcloud.controller;
    
    import com.zhao.springcloud.pojo.dept;
    import com.zhao.springcloud.service.deptServiceImpl;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    
    @RestController
    public class deptController {
        @Autowired
        deptServiceImpl deptService;
    
        @PostMapping("/dept/add")
        public Boolean addDept(dept dept){
            return deptService.addDept(dept);
        }
        @GetMapping("/dept/add/{deptno}")
        public dept queryDeptById(@PathVariable("deptno") long deptno){
            return deptService.queryDeptById(deptno);
        }
        @GetMapping("/dept/addAll")
        public List<dept> queryAll(){
            return deptService.queryAll();
        }
    }
    
    
  4. 编写启动类启动测试

    package com.zhao.springcloud;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class DeptProvider_8001 {
        public static void main(String[] args) {
            SpringApplication.run(DeptProvider_8001.class,args);
        }
    }
    
    

使用服务者

通过RestTemplate即可动态通过网址去本地调用

<?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">
    <parent>
        <artifactId>springcloud</artifactId>
        <groupId>com.zhao</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud-consumer-dept-80</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.zhao</groupId>
            <artifactId>springcloud-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.4.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <version>2.4.4</version>
        </dependency>
    </dependencies>

</project>

把RestTemplate注册到spring中方便使用

package com.zhao.springcloud.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestConfig {
    @Bean
    public RestTemplate getRest(){
        return new RestTemplate();
    }
}

package com.zhao.springcloud.controller;

import com.zhao.springcloud.pojo.dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;


@RestController
public class deptConsumerController {
    private final String PREFIX = "http://localhost:8001";
    @Autowired
    RestTemplate restTemplate;

    @RequestMapping("/consumer/getdept/{id}")
    public dept getDeptById(@PathVariable("id") long id){
        return restTemplate.getForObject(PREFIX+"/dept/get/"+id, dept.class);
    }
    @RequestMapping("/consumer/getdept")
    public List<dept> getAll(){
        return restTemplate.getForObject(PREFIX+"/dept/getAll", List.class);
    }
    @RequestMapping("/consumer/adddept")
    public boolean addDept(String dname){
        return restTemplate.postForObject(PREFIX+"/dept/add",dname, Boolean.class);

    }

}
package com.zhao.springcloud;

import javafx.application.Application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

Eureka 注册中心

导包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <version>2.4.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka-server</artifactId>
    <version>1.4.7.RELEASE</version>
</dependency>

配置

server:
  port: 7001
eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false  #不把自己注册到注册中心
    fetch-registry: false   #为false说明自己是个注册中心
    service-url:  #监控页面
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

开启eureka并启动测试

package com.zhao.springcloud;
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);
    }
}

使用服务者整合eureka

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
    <version>1.4.7.RELEASE</version>
</dependency>
server:
  port: 8001
  #mybatis的配置
mybatis:
  type-aliases-package: com/zhao/springcloud/pojo
  mapper-locations: classpath:com/zhao/mapper/*.xml
#spring的配置
spring:
  application:
    name: springcloud-provide-dept
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=UTF-8&useSSL=false
eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka/
package com.zhao.springcloud;

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

@SpringBootApplication
@EnableEurekaClient
public class DeptProvider_8001 {
    public static void main(String[] args) {
        SpringApplication.run(DeptProvider_8001.class,args);
    }
}

集群的配置

例如三个,写三个相同的eureka注册中心即可,端口不同,只需要对配置文件修改一下即可

集群1

server:
  port: 7001
eureka:
  instance:
    hostname: eureka7001.com
  client:
    register-with-eureka: false  #不把自己注册到注册中心
    fetch-registry: false   #为false说明自己是个注册中心
    service-url: #监控页面,单个注册中心写自己http://${eureka.instance.hostname}:${server.port}/eureka/
      # 集群写其余的注册中心地址即可,相当于把自己和谁关联
      defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

集群2

server:
  port: 7002
eureka:
  instance:
    hostname: eureka7002.com
  client:
    register-with-eureka: false  #不把自己注册到注册中心
    fetch-registry: false   #为false说明自己是个注册中心
    service-url: #监控页面,单个注册中心写自己http://${eureka.instance.hostname}:${server.port}/eureka/
      # 集群写其余的注册中心地址即可,相当于把自己和谁关联
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7003.com:7003/eureka/

集群3

server:
  port: 7003
eureka:
  instance:
    hostname: eureka7003.com
  client:
    register-with-eureka: false  #不把自己注册到注册中心
    fetch-registry: false   #为false说明自己是个注册中心
    service-url:  #监控页面,单个注册中心写自己http://${eureka.instance.hostname}:${server.port}/eureka/
                  # 集群写其余的注册中心地址即可,相当于把自己和谁关联
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

服务提供者

server:
  port: 8001
  #mybatis的配置
mybatis:
  type-aliases-package: com/zhao/springcloud/pojo
  mapper-locations: classpath:com/zhao/mapper/*.xml
#spring的配置
spring:
  application:
    name: springcloud-provide-dept
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=UTF-8&useSSL=false
eureka:
  client:
    service-url:   #相当于把自己和谁关联,相当于把自己交给了谁管理
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

客户端整合ribbon(负载均衡)

  1. 需要添加ribbon和eureka的依赖

    <!--       客户端需要从eureka中找服务地址,并通过负载均衡,所以导入ribbon和eureka=的包-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-ribbon</artifactId>
                <version>1.4.7.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-eureka</artifactId>
                <version>1.4.7.RELEASE</version>
            </dependency>
    
  2. 编写配置,与哪些eureka地址关联

    server:
      port: 80
    eureka:
      client:
        register-with-eureka: false
        service-url:
          defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
    
  3. 把RestTemlate交给spring方便之后的调用,并且使用注解标记这个类是负载均衡方式

    @Configuration
    public class RestConfig {
        @Bean
        @LoadBalanced
        public RestTemplate getRest(){
            return new RestTemplate();
        }
    }
    
  4. controller层,前缀地址换成服务提供者在eureka中的名称

    @RestController
    public class deptConsumerController {
        //private final String PREFIX = "http://localhost:8001";
        private final String PREFIX = "http://SPRINGCLOUD-PROVIDE-DEPT";
        @Autowired
        RestTemplate restTemplate;
    
        @RequestMapping("/consumer/getdept/{id}")
        public dept getDeptById(@PathVariable("id") long id){
            return restTemplate.getForObject(PREFIX+"/dept/get/"+id, dept.class);
        }
        @RequestMapping("/consumer/getdept")
        public List<dept> getAll(){
            return restTemplate.getForObject(PREFIX+"/dept/getAll", List.class);
        }
        @RequestMapping("/consumer/adddept")
        public boolean addDept(String dname){
            return restTemplate.postForObject(PREFIX+"/dept/add",dname, Boolean.class);
    
        }
    
    }
    

ribbon实现负载均衡

由于ribbon负载均衡是针对多个提供者通过特定算法选择对哪个提供者进行调度,因此增加了两个服务提供者,增加时注意修改端口,数据库即可。

(略)

feign实现负载均衡

添加feign的依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
    <version>1.4.7.RELEASE</version>
</dependency>

需要在service层写一个接口,标注feignClient,属性写eureka里的服务名称,接口写对用的方法和对应的访问路径

package com.zhao.springcloud.service;

import com.zhao.springcloud.pojo.dept;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@FeignClient(value = "SPRINGCLOUD-PROVIDE-DEPT")
@Service
@Component
public interface feignService {
    @PostMapping("/dept/add")
    public boolean addDept(dept dept);
    @GetMapping("/dept/get/{deptno}")
    public dept getDeptById(@PathVariable("deptno") long id);
    @RequestMapping("/dept/discovery")
    public List<dept> getAll();
}

使用服务者的controller层得到这个接口的bean并,在相应的方法上调用对应的方法

package com.zhao.springcloud.controller;

import com.zhao.springcloud.pojo.dept;
import com.zhao.springcloud.service.feignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.util.List;


@RestController
public class deptConsumerController {
    //private final String PREFIX = "http://localhost:8001";
    //private final String PREFIX = "http://SPRINGCLOUD-PROVIDE-DEPT";

//    @Autowired
//    RestTemplate restTemplate;

    @Autowired
    feignService feignService;

    @RequestMapping("/consumer/getdept/{id}")
    public dept getDeptById(@PathVariable("id") long id){
        return feignService.getDeptById(id);

    }
    @RequestMapping("/consumer/getdept")
    public List<dept> getAll(){
        return feignService.getAll();
    }
    @RequestMapping("/consumer/adddept")
    public boolean addDept(dept dept){
        return feignService.addDept(dept);
    }
}

启动类上开启feign的支持并扫描然后测试

package com.zhao.springcloud;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients()
public class ApplicationDeptConsumer {
    public static void main(String[] args) {
        SpringApplication.run(ApplicationDeptConsumer.class,args);
    }
}

hystrix熔断机制(整合到服务提供者)

添加依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
    <version>1.4.7.RELEASE</version>
</dependency>

controller中使用hystrix的注解,来实现对错误信息的重新定义

package com.zhao.springcloud.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import com.zhao.springcloud.pojo.dept;
import com.zhao.springcloud.service.deptServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class deptController {
    @Autowired
    deptServiceImpl deptService;

    @HystrixCommand(fallbackMethod = "myFull") //这个注解说明此方法抛出异常后会调用对应的其他方法
    @GetMapping("/dept/get/{deptno}")
    public dept queryDeptById(@PathVariable("deptno") long deptno){
        dept dept = deptService.queryDeptById(deptno);
        if(dept==null){
            throw  new RuntimeException("error");
        }
        return deptService.queryDeptById(deptno);
    }


    private dept myFull(@PathVariable("deptno") long id){
        return new dept().setDeptno(id).setDname("查无此人---Hystrix").setDb_source("数据库中没有这个信息");
    }
}

启动类上开启熔断机制并测试

package com.zhao.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker //开启熔断机制
public class DeptProviderHystrix_8001 {
    public static void main(String[] args) {
        SpringApplication.run(DeptProviderHystrix_8001.class,args);
    }
}

hystrix服务降级(整合到客户端)

在公共模块中的service写个类,实现FallbackFactory接口,重写方法,返回对应的feignService接口

package com.zhao.springcloud.service;

import com.zhao.springcloud.pojo.dept;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class myFallBackFactory implements FallbackFactory {
    @Override
    public feignService create(Throwable throwable) {
        return new feignService() {
            @Override
            public boolean addDept(dept dept) {
                return false;
            }

            @Override
            public dept getDeptById(long id) {
                return new dept().setDeptno(id).setDname("服务已经被关闭,Hystrix==》").setDb_source("连接数据库失败");
            }

            @Override
            public List<dept> getAll() {
                return null;
            }
        };
    }
}

把上面的类当作feign的失败调用类。

package com.zhao.springcloud.service;

import com.zhao.springcloud.pojo.dept;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@FeignClient(value = "SPRINGCLOUD-PROVIDE-DEPT",fallbackFactory = myFallBackFactory.class)
@Service
@Component
public interface feignService {
    @PostMapping("/dept/add")
    public boolean addDept(dept dept);
    @GetMapping("/dept/get/{deptno}")
    public dept getDeptById(@PathVariable("deptno") long id);
    @RequestMapping("/dept/discovery")
    public List<dept> getAll();
}

在服务使用者中的配置信息中 打开降级服务

server:
  port: 80
eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

#打开hystrix服务降级开关
feign:
  hystrix:
    enabled: true

测试: 首先打开eureka服务中心,在打开服务提供者把服务注册到服务中心,打开服务使用者,进入服务中心,通过自己拿到的服务id去找对应的服务,找到后,调用对应的方法即可。若找不到,就会调用自身的失败调用的类中去调用对应方法。即,当服务提供者断掉的时候,客户端仍然可以使用事先在自身内部就设置好的方法去执行,不至于客户访问不到。

dashboard监控页面

写一个监控模块,引入dashboard和hystrix依赖,修改对应端口,启动类上添加启动dashboard注解

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
    <version>1.4.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
    <version>1.4.7.RELEASE</version>
</dependency>
server:
  port: 9001

hystrix:
  dashboard:
    proxy-stream-allow-list: "localhost"
@SpringBootApplication
@EnableHystrixDashboard
public class dashboardApplication {
    public static void main(String[] args) {
        SpringApplication.run(dashboardApplication.class,args);
    }
}

启动eureka服务

服务提供者也添加dashboard和hystrix依赖和允许监控的依赖。启动类添加监控地址映射。,启动。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
    <version>1.4.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
    <version>1.4.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
    <version>2.4.4</version>
</dependency>

@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class DeptProviderHystrix_8001 {
    public static void main(String[] args) {
        SpringApplication.run(DeptProviderHystrix_8001.class,args);
    }

    @Bean
    public ServletRegistrationBean servletRegistrationBean(){
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new HystrixMetricsStreamServlet());
        servletRegistrationBean.addUrlMappings("/hystrix.stream");
        return servletRegistrationBean;
    }
}

访问dashboard页面,填入要=监控的映射页面,即可

http://localhost:9001/hystrix

http://localhost:8001/hystrix.stream

Zuul路由跳转

写一个zuul的模块,添加Eureka和zuul的依赖,

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

配置自己的服务名,eureka注册地址,替换访问的路径

server:
  port: 8001
  #mybatis的配置
mybatis:
  type-aliases-package: com/zhao/springcloud/pojo
  mapper-locations: classpath:com/zhao/mapper/*.xml
#spring的配置
spring:
  application:
    name: springcloud-provide-dept
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=UTF-8&useSSL=false
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

启动类开启Zuul

@SpringBootApplication
@EnableZuulProxy
public class zuul9527Application {
    public static void main(String[] args) {
        SpringApplication.run(zuul9527Application.class,args);
    }
}

Config

Git搭建

码云创建项目,git clone 项目地址 ,把项目下载到当前目录,添加配置文件,再上传到码云上,

上传命令:

git add .

git status

git commit -m “1”

git push origin master

配置服务端连接码云

添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-config-server -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
    <version>2.2.7.RELEASE</version>
</dependency>

编写配置

server:
  port: 3307
spring:
  application:
    name: spring-config-3307
  cloud:
    config:
      server:
        git:
          uri: https://gitee.com/ipanp/springcloud.git

启动类开启config

@SpringBootApplication
@EnableConfigServer
public class Configserver3307 {
    public static void main(String[] args) {
        SpringApplication.run(Configserver3307.class,args);
    }

启动测试

http://localhost:3307/application-test.yaml

配置客户端连接配置服务端

添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-config -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
    <version>2.2.7.RELEASE</version>
</dependency>

写配置项

spring:
  cloud:
    config:
      uri: http://localhost:3307
      profile: dev
      name: config-client
      label: master

controller层注入属性

@RestController
public class configController {
    @Value("${server.port}")
    private String port;
    @Value("${eureka.client.service-url.defaultZone}")
    private String eurekaName;
    @Value("${spring.profiles}")
    private String profiles;

    @RequestMapping("/config")
    public String config(){
        return "eurekaName:"+eurekaName+
         ",profiles:"+profiles+
         ",port:"+port;
    }

启动测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值