Spring Cloud微服务之Feign服务调用(十一)


一、Feign简介

基本概念

Feign是Netflix开发的声明式、模板化的HTTP客户端
Feign可以帮助我们更快捷、优雅地调用HTTP API。
Feign支持多种注解,例如Feign自带的注解或者JAX-RS注解等。
Spring Cloud对Feign进行了增强,使Feign支持了Spring MVC注解,并整合了Ribbon和Eureka,从而让Feign的使用更加方便。

Spring Cloud Feign是基于Netflix feign实现,整合了Spring Cloud Ribbon和Spring Cloud Hystrix,除了提供这两者的强大功能外,还提供了一种声明式的Web服务客户端定义的方式。
Spring Cloud Feign帮助我们定义和实现依赖服务接口的定义。在Spring Cloud feign的实现下,只需要创建一个接口并用注解方式配置它,即可完成服务提供方的接口绑定,简化了在使用Spring Cloud Ribbon时自行封装服务调用客户端的开发量。

二、实现服务调用

在我们搭建好的service_file模块中,编写删除源文件的接口。

1、编写删除源文件接口

CrmFileController.java

 //根据文件 url 删除源文件
 @PostMapping(value = "removeCrmFileById/{id}")
 public ResultBean removeCrmFileById(@PathVariable Integer id){
     return crmFileService.removeCrmFileById(id);
 }

CrmFileServiceImpl.java接口实现类

@Override
public ResultBean removeCrmFileById(Integer id) {
    //查询源文件真实的 url
    CrmFile crmFile = baseMapper.selectById(id);
    String url = crmFile.getUrl();

    //根据url 删除源文件
    if(!StringUtils.isEmpty(url)){
        File folder =new File(url);
        boolean flag = folder.delete();
        if(flag){
            return ResultBean.ok();  //删除成功
        }else {
            return ResultBean.error(); //删除失败
        }
    }else {
        return ResultBean.error().message("源文件不存在,无法删除");
    }
}

2、在service模块添加pom依赖

 <!--服务调用-->
 <dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-openfeign</artifactId>
 </dependency>

3、在调用端(service_user)的启动类添加注解

@EnableFeignClients   //服务调用

在这里插入图片描述

4、新建一个包client、里面新建一个类FileClient.java

在这里插入图片描述
FileClient.java

@FeignClient("service-file")   //@FeignClient注解用于指定从哪个服务中调用功能 ,名称与被调用的服务名保持一致。
@Component  //交给spring管理
public interface FileClient {

    //根据文件 url 删除源文件
    @PostMapping(value = "/fileservice/crm-file/removeCrmFileById/{id}")  //这个路径映射,是全路径映射
    public ResultBean removeCrmFileById(@PathVariable("id") Integer id); //@PathVariable注解一定要指定参数名称,否则出错

}

注意:@PostMapping(value = “/fileservice/crm-file/removeCrmFileById/{id}”)
是service_file模块中的这个方法的全映射路径
在这里插入图片描述

5、调用微服务(在service_user模块中)

在这里插入图片描述
我们上一篇写的代码,我们重新改造。 @PostMapping(value = “/fileservice/crm-file/removeCrmFileById/{id}”) 这个接口中我们只需要传入该条记录的id,他就能帮我们实现源文件的删除。

1、首先注入FileClient

 //已经交给spring管理了、我们直接注入使用
    @Autowired
    private FileClient fileClient;

2、修改删除数据接口代码

 //根据id、删除删除源文件+删除数据库数据记录
 @PostMapping(value = "removeCrmFile/{id}")
 public ResultBean removeCrmFile(@PathVariable Integer id){
     //1、调用service_file模块服务接口,实现源文件删除
     if(id != null){
         System.out.println("开始调用...");
         ResultBean resultBean = fileClient.removeCrmFileById(id);
         if(resultBean.getCode() == 2001){
             System.out.println("删除失败...");
         }
         System.out.println("调用结束...");
     }
     //2、最后删除数据库记录
     boolean remove = crmFileService.removeById(id);
     if (remove){
         return ResultBean.ok();
     }else {
         return ResultBean.error();
     }
 }

3、提前准好好数据库数据

在这里插入图片描述
注意:url 真实路径下面放一张图片,方便测试。
在这里插入图片描述

6、启动项目测试

首先启动两个模块,service_user和service_file,9901端口和9902端口
发送POST请求:http://localhost:9901/eduservice/crm-file/removeCrmFile/3
在这里插入图片描述
控制台打印输出

开始调用...
2020-05-15 01:36:03.618  INFO 9208 --- [nio-9901-exec-1] c.netflix.config.ChainedDynamicProperty  : Flipping property: service-file.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2020-05-15 01:36:03.733  INFO 9208 --- [nio-9901-exec-1] c.netflix.loadbalancer.BaseLoadBalancer  : Client: service-file instantiated a LoadBalancer: DynamicServerListLoadBalancer:{NFLoadBalancer:name=service-file,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
2020-05-15 01:36:03.754  INFO 9208 --- [nio-9901-exec-1] c.n.l.DynamicServerListLoadBalancer      : Using serverListUpdater PollingServerListUpdater
2020-05-15 01:36:03.794  INFO 9208 --- [nio-9901-exec-1] c.netflix.config.ChainedDynamicProperty  : Flipping property: service-file.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2020-05-15 01:36:03.796  INFO 9208 --- [nio-9901-exec-1] c.n.l.DynamicServerListLoadBalancer      : DynamicServerListLoadBalancer for client service-file initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=service-file,current list of Servers=[192.168.162.1:9902],Load balancer stats=Zone stats: {unknown=[Zone:unknown;	Instance count:1;	Active connections count: 0;	Circuit breaker tripped count: 0;	Active connections per server: 0.0;]
},Server stats: [[Server:192.168.162.1:9902;	Zone:UNKNOWN;	Total Requests:0;	Successive connection failure:0;	Total blackout seconds:0;	Last connection made:Thu Jan 01 08:00:00 CST 1970;	First connection made: Thu Jan 01 08:00:00 CST 1970;	Active Connections:0;	total failure count in last (1000) msecs:0;	average resp time:0.0;	90 percentile resp time:0.0;	95 percentile resp time:0.0;	min resp time:0.0;	max resp time:0.0;	stddev resp time:0.0]
]}ServerList:org.springframework.cloud.alibaba.nacos.ribbon.NacosServerList@7cc3506c
调用结束...

MySQL中查看数据库、本地盘符下查看源文件、是不是就都不存在了,成功删除了源文件,删除了数据记录,实现了服务间的调用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Cloud微服务架构中,Nacos是一个注册中心和配置中心。Feign是一个声明式的Web服务客户端,它使得编写Web服务客户端变得更加容易。 使用Feign调用接口需要以下步骤: 1. 在pom.xml中添加Feign依赖 ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> ``` 2. 在启动类上添加@EnableFeignClients注解启用Feign客户端 ```java @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 3. 创建接口,并使用@FeignClient注解指定调用服务名称和服务路径 ```java @FeignClient(name = "service-provider") public interface UserService { @GetMapping("/user/{id}") String getUserById(@PathVariable("id") Long id); } ``` 其中,name属性指定服务名称,GetMapping注解指定服务路径。 4. 在需要使用该服务的地方注入UserService并调用方法即可 ```java @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/user/{id}") public String getUserById(@PathVariable("id") Long id) { return userService.getUserById(id); } } ``` 在这个例子中,我们定义了一个名为UserService的Feign客户端,指定了调用服务名称和服务路径。然后在UserController中注入了UserService并调用了其方法。最终,Feign会自动将该请求转发到名为service-provider的微服务,并返回结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DT辰白

你的鼓励是我创作的源泉

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值