spring cloud openfeign笔记

本文详细介绍了如何在微服务架构中使用Feign客户端进行服务间调用,包括配置Consul作为服务注册中心,通过Spring Cloud OpenFeign实现服务调用,以及配置超时机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前面记录服务的注册发现相关笔记是采用RestTemplate+LoadBalancerClient,有一个框架封装了微服务之间的调用,就是这个玩意。服务注册前面记录过了,这里就不说了https://my.oschina.net/uwith/blog/1929697,主要说下客户端,也就是调用服务的实现。服务注册中心是使用consul实现的。

1、老规矩在客户端先添加pom引用

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

2、application.yml配置文件添加配置信息。

server:
  port: 8082
spring:
  application:
    name: client-test
  cloud:
    consul:
      host: 192.168.1.1
      port: 8500
      discovery:
        #不注册到consul
        register: false

3、在application启动类上添加一个注解。不添加@EnableFeignClients注解,定义的接口会注入不进去。

@EnableFeignClients
@SpringBootApplication
public class ClientTestApplication {
    public static void main(String[] args) {
        SpringApplication.run(ClientTestApplication.class, args);
    }
}

4、需要建立一个接口,来生成调用对象。@RequestMapping这个注解就表示调用服务的路径,我这个路径就是http://server-test/index

package com.example.clienttest.web;

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

@Component
//调用服务中的注册服务名称
@FeignClient("server-test")
public interface FeignClientsTest {
    @RequestMapping(value = "index")
    String index();
}

5、然后测试类

package com.example.clienttest.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {

    @Autowired
    FeignClientsTest feignClientsTest;

    @RequestMapping("/index")
    public String index() {
        String result = feignClientsTest.index();
        System.out.println("请求拿到的结果:" + result);
        return "这里是client-test";
    }
}

f26d10b42872a7a26907bb47c39a06f318d.jpg

 

这个东西也对熔断有支持,感觉和hystrix断路器使用区别不大。

注意:springcloud使用feign会自带超时机制,默认1S,可以调整配置文件信息来进行修改超时时间,ribbon.ReadTimeout和ConnectTimeout

参考链接:

https://blog.youkuaiyun.com/xslde_com/article/details/81153498

 

转载于:https://my.oschina.net/uwith/blog/3063071

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值