写点什么

Eureka(F 版本)教程三 服务消费者(Feign)

作者:Java高工P7
  • 2021 年 11 月 11 日
  • 本文字数:1365 字

    阅读完需:约 4 分钟

<parent>


<groupId>com.loren</groupId>


<artifactId>spring-cloud-demo</artifactId>


<version>1.0-SNAPSHOT</version>


</parent>


<groupId>com.loren</groupId>


<artifactId>serice-feign</artifactId>


<version>0.0.1-SNAPSHOT</version>


<name>serice-feign</name>


<packaging>jar</packaging>


<description>Demo project for Spring Boot</description>


<properties>


<java.version>1.8</java.version>


<spring-cloud.version>Greenwich.SR2</spring-cloud.version>


</properties>


<dependencies>


<dependency>


<groupId>org.springframework.cloud</groupId>


<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>


</dependency>


<dependency>


<groupId>org.springframework.boot</groupId>


<artifactId>spring-boot-starter-web</artifactId>


</dependency>


<dependency>


<groupId>org.springframework.cloud</groupId>


<artifactId>spring-cloud-starter-openfeign</artifactId>


</dependency>


</dependencies>


<build>


<plugins>


<plugin>


<groupId>org.springframework.boot</groupId>


<artifactId>spring-boot-maven-plugin</artifactId>


</plugin>


</plugins>


</build>


</project>


在工程的配置文件 application.yml 文件,指定程序名为 service-feign,端口号为 8765,服务注册地址为 http://localhost:8761/eureka/ ,代码如下:


eureka:


client:


serviceUrl:


defaultZone: http://localhost:8761/eureka/


server:


port: 8765


spring:


application:


name: service-feign


在程序的启动类 ServiceFeignApplication ,加上 @EnableFeignClients 注解开启 Feign 的功能:


@SpringBootApplication


@EnableEurekaClient


@EnableDiscoveryClient


@EnableFeignClients


public class ServiceFeignApplication {


public static void main(String[] args) {


SpringApplication.run( ServiceFeignApplication.clas


【一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义】
浏览器打开:qq.cn.hn/FTf 免费领取
复制代码


s, args );


}


}


定义一个 feign 接口,通过 @ FeignClient(“服务名”),来指定调用哪个服务。比如在代码中调用了 service-hi 服务的“/hi”接口,代码如下:


package com.loren.sericefeign.feign;


import org.springframework.cloud.openfeign.FeignClient;


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


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


import org.springframework.web.bind.annotation.RequestParam;


@FeignClient(value = "service-client")


public interface SchedualServiceHi {


@RequestMapping(value = "/hi",method = RequestMethod.GET)


String sayHiFromClientOne(@RequestParam(value = "name") String name);


}


在 Web 层的 controller 层,对外暴露一个”/hi”的 API 接口,通过上面定义的 Feign 客户端 SchedualServiceHi 来消费服务。代码如下:


package com.loren.sericefeign.controller;


import com.loren.sericefeign.feign.SchedualServiceHi;


import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.web.bind.annotation.GetMapping;


import org.springframework.web.bind.annotation.RequestParam;


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

用户头像

Java高工P7

关注

还未添加个人签名 2021.11.08 加入

还未添加个人简介

评论

发布
暂无评论
Eureka(F版本)教程三 服务消费者(Feign)