网站地图    收藏    合作   

主页 > 后端 > java >

SpringCloud之Feign远程接口映射的实现

来源:自学PHP网    时间:2020-09-27 14:39 作者:小飞侠 阅读:

[导读] SpringCloud之Feign远程接口映射的实现...

今天带来SpringCloud之Feign远程接口映射的实现教程详解

一.简介

SpringCloud是基于Restful的远程调用框架,引入Ribbon负载均衡组件后还需要客户端使用RestTemplate调用远程接口,操作起来还显得繁琐。SpringCloud提供了远程接口映射,将远程Restful服务映射为远程接口,消费端注入远程接口即可实现方法调用。

二.流程

1.新建远程接口映射模块service-api,并引入Feign接口映射依赖

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

2.编写接口映射接口

package com.vincent.service;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient("SERVICE-USER")
@RequestMapping("/service-user")
public interface IUserService {
  @GetMapping("/detail")
  Object detail(@RequestParam("id") Integer id);
}

3.配置消费端application.yml

server:
 port: 9001

eureka:
 client:
  service-url:
   defaultZone: http://localhost:7001/service-eureka/eureka
  register-with-eureka: false

4.消费端添加映射模块依赖

 <dependency>
  <groupId>com.vincent</groupId>
  <artifactId>service-api</artifactId>
  <version>1.0-SNAPSHOT</version>
</dependency>

5.客户端注入需要使用的服务接口映射

package com.vincent.controller;

import com.vincent.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class UserController {

  @Autowired
  private IUserService userService;

  @GetMapping("/detail")
  public Object detail(Integer id){
    return this.userService.detail(id);
  }
}

5.编写消费端启动类

package com.vincent;

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


@SpringBootApplication
@EnableFeignClients({"com.vincent.service"})
@EnableEurekaClient
public class ConsumerApp {
  public static void main(String[] args) {
    SpringApplication.run(ConsumerApp.class,args);
  }
}

@EnableFeignClients 定义Feign接口映射扫描包,IOC容器会自动创建接口实现类

6.访问 http://localhost:9001/detail?id=1


以上就是关于SpringCloud之Feign远程接口映射的实现全部内容,感谢大家支持自学php网。

自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习

京ICP备14009008号-1@版权所有www.zixuephp.com

网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com

添加评论