springcloud-feign服务消费者

本文介绍Feign调用服务
Feign是一个声明性的Web服务客户端。它使编写Web服务客户端变得更容易。
它具有可插入的注释支持,包括Feign注释和JAX-RS注释。Feign还支持可插拔编码器和解码器。
Feign默认集成了Ribbon

  1. 在父工程下创建一个项目
<?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>demo.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>feign-consumer</artifactId>

    <name>feign-consumer</name>

    <dependencies>
        <!-- eureka-client依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- feign依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>

  1. 修改application.yml文件
server:
  port: 8766

spring:
  application:
    #服务名称
    name: feign-consumer

eureka:
  client:
    #是否将自己注册到Eureka服务中
    register-with-eureka: true
    #是否从Eureka服务中获取注册信息
    fetch-registry: true
    #Eureka注册中心的地址,多个注册中心用,隔开
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
  1. 修改启动程序
    @EnableFeignClients注解开启Feign的功能
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class FeignConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(FeignConsumerApplication.class, args);
    }
}
  1. 创建feign接口
    @FeignClient(“服务名”)注解指定要调用的服务
    @GetMapping(“接口”)注解指定要调用的接口(支持spring mvc中的请求注解)
    基本类型传参需要用@RequestParam(“name”)注解,不使用会获取不到参数
    get请求传实体类参数需要转换成Map,并且使用@RequestParam注解
    post请求传实体类参数需要使用@RequestBody注解
@FeignClient("eureka-service")
public interface TestService {

    @GetMapping("/hello")
    String hello();
}
  1. 创建controller
@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @GetMapping("/test")
    public String test(){
        return testService.hello();
    }
}
  1. 测试接口
    浏览器访问http://localhost:8766/test

    port:8763
    port:8764

项目路径


作者博客

作者公众号
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值