Spring Cloud Demo

打印 上一主题 下一主题

主题 900|帖子 900|积分 2700

Spring Cloud Demo

本文介绍Spring Cloud 常用的组件的demo代码。gitee代码:https://gitee.com/Aes_yt/spring-cloud-demo
包括Spring Cloud Eureka,Spring Cloud Feign,Spring Cloud Hystrix,Spring Cloud Ribbon,Spring Cloud Zuul,Spring Cloud Config,Spring Cloud Sleuth。
Spring Cloud Eureka

Server

  • pom引入:
    1. <dependency>
    2.         <groupId>org.springframework.cloud</groupId>
    3.     <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    4. </dependency>
    复制代码
  • 代码:
    SpringBootApplication 启动类加入 @EnableEurekaServer注解。
  • 配置:
    1. server:
    2.   port: 8761
    3. eureka:
    4.   instance:
    5.     hostname: localhost
    6.   client:
    7.     register-with-eureka: false
    8.     fetch-registry: false
    9.     service-url:
    10.       defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
    11.   server:
    12.     wait-time-in-ms-when-sync-empty: 0
    13.     enable-self-preservation: false
    复制代码
Client

  • pom引入:
    1. <dependency>
    2.         <groupId>org.springframework.cloud</groupId>
    3.         <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    4. </dependency>
    复制代码
  • 代码:
    SpringBootApplication 启动类加入 @EnableDiscoveryClient注解。
  • 配置:
    1. server:
    2.   port: 8081
    3. spring:
    4.   application:
    5.     name: demo-client1
    6. eureka:
    7.   client:
    8.     service-url:
    9.       defaultZone: http://localhost:8761/eureka/
    复制代码
TIPS. 非java语言也可使用Eureka提供的REST API接口接入Server。 wiki
常见问题

  • 为什么服务上线了,Eureka Client 不能及时获取到。
    Eureka Server 的 REST API 有response cache,需要等缓存过期后才能更新数据。

  • 为什么服务下线了,Eureka Server 接口返回的信息还会存在。
    应用实例异常挂掉,没有在挂掉之前告知Server 要下线。这个就需要依赖Eureka Server的EvictionTask 去剔除。

  • 其他:
    springcloud对springboot的版本是有要求的,如果不一致,会启动不起来的。详细可以看官网的版本要求。

Spring Cloud Feign + Spring Cloud Hystrix

demo-hello

  • 首先先创建一个 demo 的 module,接入Eureka配置(eureka-client )。设置端口8082,里面只有一个get方法,我们用postman调用 http://localhost:8082/hello/testGet?param=hello,能够正常返回。
    1. @RestController
    2. @RequestMapping("/hello")
    3. @Slf4j
    4. public class HelloController {
    5.     @GetMapping("/testGet")
    6.     public BaseResp<String> testGet(@RequestParam("param") String param) {
    7.         log.info("[demo-hello] testGet:{}", param);
    8.         return BaseResp.success(param);
    9.     }
    10. }
    复制代码
    yml:
    1. server:
    2.   port: 8082
    3. spring:
    4.   application:
    5.     name: demo-hello
    6. eureka:
    7.   client:
    8.     service-url:
    9.       defaultZone: http://localhost:8761/eureka/
    复制代码
feign-client

  • 创建一个新module。引入Eureka-client依赖,feign依赖和hystrix依赖。
    1. <dependency>
    2.     <groupId>org.springframework.cloud</groupId>
    3.     <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    4. </dependency>
    5. <dependency>
    6.     <groupId>org.springframework.cloud</groupId>
    7.     <artifactId>spring-cloud-starter-openfeign</artifactId>
    8. </dependency>
    9. <dependency>
    10.     <groupId>org.springframework.cloud</groupId>
    11.     <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    12. </dependency>
    复制代码
    注意:hystrix 在 spring-cloud 2020.0.x 版本废弃,之后的版本推荐使用 Resilience4j 进行服务的熔断。
  • yaml 配置
    1. server:
    2.   port: 8083
    3. spring:
    4.   application:
    5.     name: feign-client
    6. eureka:
    7.   client:
    8.     service-url:
    9.       defaultZone: http://localhost:8761/eureka/
    10. feign:
    11. #  hystrix熔断开关
    12.   hystrix:
    13.     enabled: true
    14. #  feign-client的超时时间
    15.   client:
    16.     config:
    17.       default:
    18.         connect-timeout: 3000
    19.         read-timeout: 3000
    20.         logger-level: basic
    21. # 设置hystrix服务降级超时时间
    22. hystrix:
    23.   command:
    24.     default:
    25.       execution:
    26.         isolation:
    27.           thread:
    28.             timeoutInMilliseconds: 15000
    复制代码
  • Application 注解
    @EnableFeignClients:@EnableFeignClients 是一个 Spring Cloud 注解,用于启用 Feign 客户端的功能。
    @EnableCircuitBreaker:@EnableCircuitBreaker 是 Spring Cloud 提供的一个注解,用于启用熔断器(Circuit Breaker)的功能。
    1. @SpringBootApplication
    2. @EnableDiscoveryClient
    3. @EnableFeignClients
    4. @EnableCircuitBreaker
    5. public class FeignClientApplication {
    6.     public static void main(String[] args) {
    7.         SpringApplication.run(FeignClientApplication.class, args);
    8.     }
    9. }
    复制代码
  • 建立Feign调用Service
    1. @FeignClient(name = "demo-hello", contextId = "feign-hello", path = "/hello", fallbackFactory = FeignHelloServiceHystrix.class)
    2. public interface FeignHelloService {
    3.     @RequestMapping(value = "/testGet", method = RequestMethod.GET)
    4.     BaseResp<String> testGet(@RequestParam("param") String param);
    5. }
    复制代码
    name = "demo-hello" 就是 demo 项目的 spring.application.name,contentxId 就相当于这个调用service的唯一id,path就是统一前缀。fallbackFactory 就是降级后的工厂。所以我们要实现这个工厂。
    我这边的逻辑,就是记录一下日志,然后返回统一的错误对象。
    1. @Slf4j
    2. @Component
    3. public class FeignHelloServiceHystrix implements FallbackFactory<FeignHelloService> {
    4.     @Override
    5.     public FeignHelloService create(Throwable cause) {
    6.         log.error("feign调用helloController报错", cause);
    7.         return new FeignHelloService() {
    8.             public BaseResp<String> testGet(String param) {
    9.                 return BaseResp.error(param);
    10.             }
    11.         };
    12.     }
    13. }
    复制代码
  • 测试一下,
    1.     @GetMapping("/testGet")
    2.     public BaseResp<String> testGet(@RequestParam("param") String param) {
    3. //        try {
    4. //            Thread.sleep(6000);
    5. //        } catch (InterruptedException e) {
    6. //            throw new RuntimeException(e);
    7. //        }
    8. //        if(!param.isEmpty()){
    9. //            throw new RuntimeException("error...");
    10. //        }
    11.         log.info("[demo-hello] testGet:{}", param);
    12.         return BaseResp.success(param);
    13.     }
    复制代码
    testGet 6秒钟才响应或者直接抛出异常,都是会进入FeignHelloServiceHystrix中打印日志。
附加
<ol>Feign 加日志打印
<ol>xml配置Feign客户端
  1. # Feign 日志配置
  2. logging:
  3.   level:
  4.     com.yt.demo.service.feign: debug
复制代码
Feign 配置
  1. /**
  2. * Feign 配置
  3. */
  4. @Slf4j
  5. @Configuration
  6. public class FeignConfig {
  7.     /**
  8.      * NONE:不记录任何信息
  9.      * BASIC:仅记录请求方法、URL以及响应状态码和执行时间.
  10.      * HEADERS:除了记录BASIC级别的信息外,还会记录请求和响应的头信息
  11.      * FULL:记录所有请求与响应的明细,包括头信息、请求体、元数据
  12.      */
  13.     @Bean
  14.     Logger.Level feignLoggerLevel() {
  15.         return Logger.Level.FULL;
  16.     }
  17. }
复制代码
效果如下:
[code]2023-06-23 11:38:43.026 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] ---> POST http://demo-hello/hello/testPost HTTP/1.12023-06-23 11:38:43.026 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] Content-Length: 302023-06-23 11:38:43.026 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] Content-Type: application/json2023-06-23 11:38:43.026 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] 2023-06-23 11:38:43.026 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] {"param":"Post method: hello"}2023-06-23 11:38:43.026 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] ---> END HTTP (30-byte body)2023-06-23 11:38:43.029 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost]
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

天津储鑫盛钢材现货供应商

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表