springboot整合feign实现RPC调用,并通过Hystrix实现服务降级

feign/openfeign和dubbo是常用的微服务RPC框架,由于feigin内部已经集成ribbon,自带了负载均衡的功能,当有多个同名的服务注册到注册中心时,会根据ribbon默认的负载均衡算法将请求分配到不同的服务。这篇文章就简单介绍一下怎么使用feign来调用远程的服务。

首先,需要有一个微服务注册中心来提供服务注册与发现,本章就使用之前创建的eureka作为注册中心。点击以下文章链接,教你快速搭建一个eureka server

springboot整合eureka、config搭建注册中心和配置中心icon-default.png?t=N7T8https://blog.csdn.net/heyl163_/article/details/131715281

目录

一、服务提供者

二、服务消费者

三、测试效果

四、开启Hystrix实现服务降级


首先,要实现服务间的调用,需要有服务提供者和服务消费者,创建两个项目,分别用于服务提供者和服务消费者。

一、服务提供者

创建一个springboot项目,取名为provider

1、修改maven配置文件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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

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

    <groupId>com.example</groupId>
    <artifactId>provider</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
        <eureka.version>1.4.4.RELEASE</eureka.version>
    </properties>

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

            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-eureka</artifactId>
                <version>${eureka.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <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>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2、修改系统配置文件

server:
  port: 8085

spring:
  application:
    name: provider

eureka:
  instance:
    hostname: localhost
  client:
    service-url:
      defaultZone: http://${eureka.instance.hostname}:8761/eureka

3、创建一个controller

在根目录下创建controller包,然后在controller包下创建一个UserController

package com.example.provider.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author heyunlin
 * @version 1.0
 */
@RestController
@RequestMapping(path = "/user", produces = "application/json;charset=utf-8")
public class UserController {

    @RequestMapping(value = "/name", method = RequestMethod.GET)
    public String name() {
        return "heyunlin";
    }

}

4、启动类上添加@EnableDiscoveryClient注解

package com.example.provider;

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

@EnableDiscoveryClient
@SpringBootApplication
public class ProviderApplication {

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

}

二、服务消费者

1、创建一个springboot项目并命名为consumer

2、修改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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

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

    <groupId>com.example</groupId>
    <artifactId>consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
        <eureka.version>1.4.4.RELEASE</eureka.version>
    </properties>

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

            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-eureka</artifactId>
                <version>${eureka.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <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>

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

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

3、修改配置文件,注册到eureka

server:
  port: 8086

spring:
  application:
    name: consumer

eureka:
  instance:
    hostname: localhost
  client:
    service-url:
      defaultZone: http://${eureka.instance.hostname}:8761/eureka

4、通过feign调用远程的方法

根目录下创建feign包,在feign包下创建一个接口FeignService(类名不重要)

@FeignClient("provider")指定注册到eurka的服务名

@RequestMapping的路径写provider服务的控制器接口路径

package com.example.consumer.feign;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author heyunlin
 * @version 1.0
 */
@FeignClient("provider")
public interface FeignService {

    @RequestMapping(value = "/user/name", method = RequestMethod.GET)
    String name();

}

5、最后,创建一个控制器类,类名随便取

package com.example.consumer.controller;

import com.example.consumer.feign.FeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author heyunlin
 * @version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    FeignService feignService;

    @RequestMapping(value = "/name", method = RequestMethod.GET)
    public String name() {
        return feignService.name();
    }

}

这时候@Autowired会报错,找不到FeignService的bean,因为没有在启动类上面添加@EnableFeignClients注解

package com.example.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableFeignClients
@SpringBootApplication
public class ConsumerApplication {

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

}

 

三、测试效果

完成以上操作之后,依次启动euraka-server,provider和consumer

浏览器上访问consumer的控制器地址http://localhost:8086/user/name,发现成功返回了字符串。

四、开启Hystrix实现服务降级

首先需要开启hystrix

在pom.xml文件中添加配置

feign:
  hystrix:
    enabled: true

然后创建一个FeignService的实现类,交给spring管理

package com.example.consumer.feign;

import org.springframework.stereotype.Component;

/**
 * @author heyunlin
 * @version 1.0
 */
@Component
public class FeignServiceImpl implements FeignService {

    @Override
    public String name() {
        return "error";
    }

}

 最后,在FeiginService接口的的@FeiginCilent注解上指定fallback=FeignServiceImpl.class

@FeignClient(value = "provider", fallback = FeignServiceImpl.class)

完成以上配置之后,重启consumer,访问http://localhost:8086/user/name时正确调用了provider的控制器方法,得到了正确的结果。

接着把关掉provider项目,再访问,发现调用失败,成功执行了配置的降级方法,直接返回了error

好了,springboot整合feign的介绍到这里就完了,代码已开源,按需获取~

注册中心

eurekaicon-default.png?t=N7T8https://gitee.com/he-yunlin/eureka.git服务提供者

providericon-default.png?t=N7T8https://gitee.com/he-yunlin/provider.git服务消费者

consumericon-default.png?t=N7T8https://gitee.com/he-yunlin/consumer.git

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot 本身不提供 RPC 功能,但是可以使用一些第三方库来实现 RPC。下面我们以 Dubbo 为例,介绍如何在 Spring Boot 中使用 Dubbo 框架搭建 RPC 调用接口。 1. 引入 Dubbo 依赖 在 pom.xml 文件中引入 Dubbo 的依赖: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo-spring-boot-starter</artifactId> <version>2.7.12</version> </dependency> ``` 2. 配置 Dubbo 在 application.yml 文件中配置 Dubbo: ```yaml dubbo: application: name: rpc-consumer registry: address: zookeeper://127.0.0.1:2181 protocol: name: dubbo port: 20880 ``` 其中,`dubbo.application.name` 是应用名字,`dubbo.registry.address` 是注册中心地址,这里使用的是 ZooKeeper,`dubbo.protocol.name` 是协议名字,这里使用的是 Dubbo 协议,`dubbo.protocol.port` 是 Dubbo 协议端口号。 3. 定义服务接口 定义一个服务接口,例如: ```java public interface HelloService { String sayHello(String name); } ``` 4. 实现服务提供者 实现上面定义的服务接口,例如: ```java @Service public class HelloServiceImpl implements HelloService { @Override public String sayHello(String name) { return "Hello, " + name + "!"; } } ``` 在实现类上加上 `@Service` 注解,表示这是一个 Dubbo 的服务提供者。 5. 配置服务提供者 在 application.yml 文件中配置服务提供者: ```yaml dubbo: application: name: rpc-provider registry: address: zookeeper://127.0.0.1:2181 protocol: name: dubbo port: 20880 scan: base-packages: com.example.rpc.provider.service.impl ``` 其中,`dubbo.scan.base-packages` 是服务提供者扫描的包路径。 6. 定义服务消费者 定义一个服务消费者,例如: ```java @RestController public class HelloController { @Reference private HelloService helloService; @GetMapping("/hello") public String hello(@RequestParam String name) { return helloService.sayHello(name); } } ``` 在控制器中使用 `@Reference` 注解注入服务提供者实例。 7. 配置服务消费者 在 application.yml 文件中配置服务消费者: ```yaml dubbo: application: name: rpc-consumer registry: address: zookeeper://127.0.0.1:2181 scan: base-packages: com.example.rpc.consumer.controller ``` 其中,`dubbo.scan.base-packages` 是服务消费者扫描的包路径。 8. 启动服务提供者和消费者 运行服务提供者和消费者程序即可。当服务提供者启动后,服务消费者就可以通过调用服务消费者中的接口来远程调用服务提供者中的方法。 以上就是在 Spring Boot 中使用 Dubbo 框架搭建 RPC 调用接口的步骤。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值