当前位置: 首页>后端>正文

springcloud五大组件架构图 springcloud五大组件使用


目录

  • SpringCloud各组件简单介绍
  • Eureka
  • Feign
  • Ribbon
  • Hystrix
  • zuul
  • SpringCloud各组件使用方法
  • 前提准备
  • Eureka入门案例
  • 1.新建Module
  • 2.修改pom文件
  • 3.创建`application.yml`配置文件
  • 4.编写启动类
  • 5.测试
  • Feign入门案例
  • 1.分别创建`provider-server`,`consumer-server`服务
  • 2.测试
  • Ribbon入门案例
  • 1.服务提供者
  • 2.服务调用者
  • 3.测试
  • Hystrix入门案例
  • 1.改造userFeign类
  • 2.UserFeignHystrix类:
  • 3.编写测试接口
  • 4.测试
  • Zuul入门案例
  • 1.新创建一个Moudle,`zuul-server`
  • 2.测试


SpringCloud各组件简单介绍

Eureka

Eureka概述

Eureka是Netflix的一个子模块,也是核心模块之一。Eureka是一个基于REST的服务,用于定位服务,以实现云端中间层服务发现和故障转移。服务注册与发现对于微服务架构来说是非常重要的,有了服务发现与注册,只需要使用服务的标识符,就可以访问到服务,而不需要修改服务调用的配置文件了.

springcloud五大组件架构图 springcloud五大组件使用,springcloud五大组件架构图 springcloud五大组件使用_spring cloud,第1张

Feign

什么是 Feign

        Feign 是一个声明式的 Web Service 客户端。它的出现使开发 Web Service 客户端变得很简单。使用 Feign 只需要创建一个接口加上对应的注解,比如:@FeignClient 注解。 Feign 有可插拔的注解,包括 Feign 注解和 AX-RS 注解。Feign 也支持编码器和解码器,Spring Cloud Open Feign 对 Feign 进行增强支持 Spring Mvc 注解,可以像 Spring Web 一样使用 HttpMessageConverters 等。
  Feign 是一种声明式、模板化的 HTTP 客户端。在 Spring Cloud 中使用 Feign,可以做到使用 HTTP 请求访问远程服务,就像调用本地方法一样的,开发者完全感知不到这是在调用远程方法,更感知不到在访问 HTTP 请求。接下来介绍一下 Feign 的特性,具体如下:

  • 可插拔的注解支持,包括 Feign 注解和AX-RS注解。
  • 支持可插拔的 HTTP 编码器和解码器。
  • 支持 Hystrix 和它的 Fallback。
  • 支持 Ribbon 的负载均衡。
  • 支持 HTTP 请求和响应的压缩。Feign 是一个声明式的 WebService 客户端,它的目的就是让 Web Service 调用更加简单。它整合了 Ribbon 和 Hystrix,从而不需要开发者针对 Feign 对其进行整合。Feign 还提供了 HTTP 请求的模板,通过编写简单的接口和注解,就可以定义好 HTTP 请求的参数、格式、地址等信息。Feign 会完全代理 HTTP 的请求,在使用过程中我们只需要依赖注入 Bean,然后调用对应的方法传递参数即可。

Ribbon

Ribbon是什么?

        Ribbon是Netflix发布的云中间层服务开源项目,其主要功能是提供客户端实现负载均衡算法。Ribbon客户端组件提供一系列完善的配置项如连接超时,重试等。简单的说,Ribbon是一个客户端负载均衡器,我们可以在配置文件中Load Balancer后面的所有机器,Ribbon会自动的帮助你基于某种规则(如简单轮询,随机连接等)去连接这些机器,我们也很容易使用Ribbon实现自定义的负载均衡算法。

springcloud五大组件架构图 springcloud五大组件使用,springcloud五大组件架构图 springcloud五大组件使用_spring cloud_02,第2张

Hystrix

Hystrix概念及作用

        Hystrix是一个用于处理分布式系统的延迟和容错的开源库。在分布式系统里,许多依赖不可避免的会调用失败,比如超时、异常等,Hystrix能够保证在一个依赖出问题的情况下,不会导致整个服务失败,避免级联故障,以提高分布式系统的弹性。

        “断路器”本身是一种开关装置,当某个服务单元发生故障之后,通过断路器的故障监控(类似熔断保险丝),向调用方返回一个符合预期的、可处理的预备响应(FallBack),而不是长时间等待或者抛出调用方无法处理的异常,这样就保证了服务调用方的线程不会被长时间、不必要的占用,从而避免了故障在分布式系统中蔓延,乃至雪崩。

zuul

zuul是什么

zuul 是netflix开源的一个API Gateway 服务器, 本质上是一个web servlet应用。

Zuul 在云平台上提供动态路由,监控,弹性,安全等边缘服务的框架。Zuul 相当于是设备和 Netflix 流应用的 Web 网站后端所有请求的前门。

zuul的例子可以参考 netflix 在github上的 simple webapp,可以按照netflix 在github wiki 上文档说明来进行使用。

SpringCloud各组件使用方法

前提准备

分别创建provider-server,consumer-server,eureka-server,zuul-server

springcloud五大组件架构图 springcloud五大组件使用,springcloud五大组件架构图 springcloud五大组件使用_eureka_03,第3张

源码地址已在文章结尾附上!!!

Eureka入门案例

1.新建Module

创建名为eureka-server的Maven工程。

2.修改pom文件

<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-demo</artifactId>
        <groupId>com.demo</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo.eureka</groupId>
    <artifactId>eureka-server</artifactId>

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

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

</project>

3.创建application.yml配置文件

server:
  port: 8080

spring:
  application:
    #应用名称(在注册中显示的)
    name: eureka-server
eureka:
  client:
    #此客户端是否获取eureka服务器注册表上的注册信息,默认为true
    fetch-registry: false
    #实例是否在eureka服务器上注册自己的信息以供其他服务发现,默认为true,即自己注册自己。
    register-with-eureka: true
    #与Eureka注册服务中心的通信zone和url地址
    serviceUrl:
      #http://localhost:8080/eureka/eureka
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka
  #服务注册中心实例的主机名
  instance:
    hostname: 127.0.0.1
    prefer-ip-address: true
    instance-id: 127.0.0.1:8080
  server:
    #设为false,关闭自我保护,即Eureka server在云心光器件会去统计心跳失败比例在15分钟之内是否低于85%,如果低于85%,EurekaServer
    #会将这些事例保护起来,让这些事例不会过期,但是在保护器内如果刚哈这个服务提供者非正常下线了,此时服务消费者会拿到一个无效的服务
    #实例,此时调用会失败,对于这个问题需要服务消费者端有一些容错机制,如重试、断路器等;
    enable-self-preservation: false
    #扫描失效服务的间隔时间(单位是毫秒,摩恩是60*1000),即60s
    eviction-interval-timer-in-ms: 10000

4.编写启动类

package com.demo.eureka;

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);
        System.out.println("Eureka服务启动完成!");
    }

}

5.测试

浏览器访问:http://localhost:8080/,查看Eureka服务主页。

springcloud五大组件架构图 springcloud五大组件使用,springcloud五大组件架构图 springcloud五大组件使用_spring cloud_04,第4张

Feign入门案例

1.分别创建provider-server,consumer-server服务

springcloud五大组件架构图 springcloud五大组件使用,springcloud五大组件架构图 springcloud五大组件使用_spring_05,第5张

1.1:服务提供者

1.1.1:修改pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springcloud-demo</artifactId>
        <groupId>com.demo</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo.provider</groupId>
    <artifactId>provider-server</artifactId>

<!--    <properties>-->
<!--        <java.version>1.8</java.version>-->
<!--        <spring-cloud.version>2021.0.4</spring-cloud.version>-->
<!--    </properties>-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

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

        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

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

        <!--mysql  的驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--mybatis-plus 的启动器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>


    </dependencies>



</project>

1.1.2:创建application.yml配置文件

server:
  port: 8081

spring:
  application:
    name: provider-server
  #配置数据源信息
  datasource:
    #配置连接数据库的各个信息
    driver-class-name: com.mysql.cj.jdbc.Driver
    #设置字符集
    url: jdbc:mysql://8.142.127.37:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true
    username: root
    password: 123456
  servlet:
    multipart:
      max-file-size: 2048MB
      max-request-size: 4096MB


mybatis-plus:
  #配置类型别名所对应的包
  type-aliases-package: com.demo.provider.entity
  #配置SQL输出语句com.winsun.dataclean.mapper
  mapper-locations: com/demo/provider/mapper/*.xml

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8080/eureka
  #服务注册中心实例的主机名
  instance:
    hostname: 127.0.0.1
    prefer-ip-address: true
    instance-id: 127.0.0.1:8081

feign:
  hystrix:
    enabled: true

1.1.3:user实体类

package com.demo.provider.entity;

import lombok.Data;

/**
 * @Author: laz
 * @CreateTime: 2022-11-02  16:38
 * @Version: 1.0
 */
@Data
public class User {

    private Long id;

    private String name;

    private String age;

    private String sex;
}

1.1.4:mapper

package com.demo.provider.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.demo.provider.entity.User;

/**
 * @Author: laz
 * @CreateTime: 2022-11-02  16:39
 * @Version: 1.0
 */
public interface UserMapper extends BaseMapper<User> {
}

1.1.5:service

package com.demo.provider.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.demo.provider.entity.User;

public interface IUserService extends IService<User> {

    User selectUserById(Long id);
}

实现类:

package com.demo.provider.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.provider.entity.User;
import com.demo.provider.mapper.UserMapper;
import com.demo.provider.service.IUserService;
import org.springframework.stereotype.Service;

/**
 * @Author: laz
 * @CreateTime: 2022-11-02  16:40
 * @Version: 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Override
    public User selectUserById(Long id) {
        return getById(id);
    }
}

1.1.6:controller

package com.demo.provider.controller;

import com.demo.provider.entity.User;
import com.demo.provider.service.IUserService;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: laz
 * @CreateTime: 2022-11-02  16:42
 * @Version: 1.0
 */
@RestController
@RequestMapping("/provider")
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping("selectUserById/{id}")
    public User selectUserById(@PathVariable("id")Long id){
        return userService.selectUserById(id);
    }
}

1.2:服务调用者

1.2.1:pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springcloud-demo</artifactId>
        <groupId>com.demo</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo.consumer</groupId>
    <artifactId>consumer-server</artifactId>

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

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

        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

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

        <!--mysql  的驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--mybatis-plus 的启动器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>


    </dependencies>


</project>

1.2.2:application.yml

server:
  port: 8082

spring:
  application:
    name: consumer-server
  #配置数据源信息
  datasource:
    #配置连接数据库的各个信息
    driver-class-name: com.mysql.cj.jdbc.Driver
    #设置字符集
    url: jdbc:mysql://8.142.127.37:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true
    username: root
    password: 123456
  servlet:
    multipart:
      max-file-size: 2048MB
      max-request-size: 4096MB


mybatis-plus:
  #配置类型别名所对应的包
  type-aliases-package: com.demo.consumer.entity
  #配置SQL输出语句com.winsun.dataclean.mapper
  mapper-locations: com/demo/consumer/mapper/*.xml

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8080/eureka
  #服务注册中心实例的主机名
  instance:
    hostname: 127.0.0.1
    prefer-ip-address: true
    instance-id: 127.0.0.1:8082

feign:
  hystrix:
    enabled: true

1.2.3:userFeign

package com.demo.consumer.feign;

import com.demo.consumer.entity.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(value = "provider-server")
public interface UserFeign {


    @GetMapping("/provider/selectUserById/{id}")
    User selectUserById(@RequestParam("id")Long id);

}

1.2.4:controller

package com.demo.consumer.controller;

import com.demo.consumer.entity.User;
import com.demo.consumer.feign.UserFeign;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: laz
 * @CreateTime: 2022-11-02  16:45
 * @Version: 1.0
 */
@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    @Autowired
    private UserFeign userFeign;

    @GetMapping("selectById/{id}")
    public User selectById(@PathVariable("id")Long id){
        return userFeign.selectUserById(id);
    }
}

2.测试

分别启动provider-server,consumer-server,eureka-server服务
浏览器访问:http://localhost:8082/consumer/selectById/1

结果:

springcloud五大组件架构图 springcloud五大组件使用,springcloud五大组件架构图 springcloud五大组件使用_java_06,第6张

Ribbon入门案例

1.服务提供者

使用RestTemplate进行Eureka Client(包括服务提供者以及服务消费者,在这里其实是服务消费者使用RestTemplate)之间的通信,为RestTemplate配置类添加@LoadBalanced注解即可。

package com.demo.provider;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
@MapperScan("com.demo.provider.mapper")
public class ProviderServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProviderServerApplication.class, args);
        System.out.println("服务提供者启动成功!");
    }

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

}

2.服务调用者

2.1:使用RestTemplate进行Eureka Client(包括服务提供者以及服务消费者,在这里其实是服务消费者使用RestTemplate)之间的通信,为RestTemplate配置类添加@LoadBalanced注解即可。

package com.demo.consumer;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableHystrix
@MapperScan("com.demo.consumer.mapper")
public class ConsumerServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerServerApplication.class, args);
        System.out.println("服务调用者启动成功");
    }


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

}

2.2:service

package com.demo.consumer.service;

import com.demo.consumer.entity.User;

public interface IUserService {

    User getUser(Long id);
}

实现类:

package com.demo.consumer.service.impl;

import com.demo.consumer.entity.User;
import com.demo.consumer.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: laz
 * @CreateTime: 2022-11-02  17:23
 * @Version: 1.0
 */
@Service
public class UserServiceImpl implements IUserService {

    /**
     * 微服务的虚拟id
     */
    private static final String REST_URL_PREFIX = "http://provider-server";

    @Autowired
    private RestTemplate restTemplate;



    @Override
    public User getUser(Long id) {
        return restTemplate.getForObject(REST_URL_PREFIX + "/provider/selectUserById/" + id, User.class);
    }
}

2.3:controller

package com.test.user.controller;

import com.test.user.service.IUserService;
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;

/**
 * @Author: laz
 * @CreateTime: 2022-10-28  11:37
 * @Version: 1.0
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private IUserService userService;
    
    @RequestMapping("getById2/{id}")
    public String getById2(@PathVariable("id")Long id){
        String byId = userService.getByFeign(id);
        return byId;
    }
}

3.测试

重启provider-server,cosumer-server

浏览器访问:http://localhost:8082/consumer/selectById2/1

结果:

springcloud五大组件架构图 springcloud五大组件使用,springcloud五大组件架构图 springcloud五大组件使用_eureka_07,第7张

Hystrix入门案例

1.改造userFeign类

只需要在FeignClient的userFeign接口的注解中加上fallback的指定类就行了

package com.demo.consumer.feign;

import com.demo.consumer.entity.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(value = "provider-server",fallback = UserFeignHystrix.class)
public interface UserFeign {


    @GetMapping("/provider/selectUserById/{id}")
    User selectUserById(@RequestParam("id")Long id);

}

2.UserFeignHystrix类:

package com.demo.consumer.feign;

import com.demo.consumer.entity.User;
import org.springframework.stereotype.Component;

@Component
public class UserFeignHystrix implements UserFeign {


    @Override
    public User selectUserById(Long id) {
        User user = new User();
        user.setName("异常用户");
        return user;
    }
}

3.编写测试接口

service:

package com.demo.consumer.service;

import com.demo.consumer.entity.User;
import org.springframework.web.bind.annotation.RequestParam;

public interface IUserService {

    User selectUserById(Long id);
}

实现类:

package com.demo.consumer.service.impl;

import com.demo.consumer.entity.User;
import com.demo.consumer.feign.UserFeign;
import com.demo.consumer.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: laz
 * @CreateTime: 2022-11-02  17:23
 * @Version: 1.0
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserFeign userFeign;

    @Override
    public User selectUserById(Long id) {
        return userFeign.selectUserById(id);
    }
}

controller:

package com.demo.consumer.controller;

import com.demo.consumer.entity.User;
import com.demo.consumer.service.IUserService;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: laz
 * @CreateTime: 2022-11-02  16:45
 * @Version: 1.0
 */
@RestController
@RequestMapping("/consumer")
public class ConsumerController {


    @Autowired
    private IUserService userService;

    @GetMapping("selectUserById/{id}")
    public User selectUserById(@PathVariable("id")Long id){
        return userService.selectUserById(id);
    }

}

4.测试

重启consumer-server服务,调用http://localhost:8082/consumer/selectUserById/1

结果:

springcloud五大组件架构图 springcloud五大组件使用,springcloud五大组件架构图 springcloud五大组件使用_java_08,第8张

此时,停掉provider-server服务,再次访问http://localhost:8082/consumer/selectUserById/1

springcloud五大组件架构图 springcloud五大组件使用,springcloud五大组件架构图 springcloud五大组件使用_spring cloud_09,第9张

可以看到,服务已被降级!

Zuul入门案例

1.新创建一个Moudle,zuul-server

springcloud五大组件架构图 springcloud五大组件使用,springcloud五大组件架构图 springcloud五大组件使用_java_10,第10张

1.1.修改pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springcloud-demo</artifactId>
        <groupId>com.demo</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo.zuul</groupId>
    <artifactId>zuul-server</artifactId>

    <dependencies>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</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-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>



</project>

1.2.添加application.yml配置文件

server:
  port: 8888
spring:
  application:
    name: zuul-service

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8080/eureka/

zuul:
  routes:
    provider-server:
      path: /provider-server/**
      serviceId: provider-server
    consumer-server:
      path: /consumer-server/**
      serviceId: consumer-server

1.3.添加启动类

package com.demo.zuul;

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

@EnableZuulProxy
@EnableEurekaClient
@SpringBootApplication
public class ZuulServerApplication {

	public static void main(String[] args) {
		SpringApplication.run(ZuulServerApplication.class, args);
		System.out.println("网关服务启动成功");
	}
}

2.测试

重启服务,然后浏览器访问http://localhost:8888/provider-server/provider/selectUserById/1

结果:

springcloud五大组件架构图 springcloud五大组件使用,springcloud五大组件架构图 springcloud五大组件使用_java_11,第11张

可以看到,成功访问到provider-server服务的接口。


https://www.xamrdz.com/backend/38w1962912.html

相关文章: