OpenFeign(负载均衡)使用详解

525 阅读1分钟

OpenFeign简介

​ OpenFeign是Spring Cloud家族中的成员之一,是一种声明式\模块化的HTTP客户端.最核心的作用是为 HTTP 形式的 Rest API 提供了非常简洁高效的 RPC 调用方式

项目结构

image-20220927194105902

1 在pom.xml中添加了相关依赖

      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

2在application.yml进行配置

主要配置端口和注册中心地址

server:
  port: 8085
spring:
  application:
    name: springcloud-openfeign
eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:8081/eureka/
 

超时配置

#微服务调用超时配置
feign:
  client:
    config:
      default:  #default指定对所有的微服务有效,可以指定具体的微服务名
        connectTimeout: 5000
        readTimeout: 5000
 

日志

#微服务调用超时配置
feign:
  client:
    config:
      default:  #default指定对所有的微服务有效,可以指定具体的微服务名
        connectTimeout: 5000
        readTimeout: 5000
        loggerLevel: full      #OpenFeign输出日志信息
logging:
  level:
    FeignClient的全限定名: debug

3编写openfeign调用接口

package com.woniuxy.openfeign.service;

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

@FeignClient(name = "serviceA")
@Component
public interface MyInfo {
 
    @RequestMapping(value = "/a", method = RequestMethod.GET)
    String getUser();
 
}

4编写controller

package com.woniuxy.openfeign.controller;


import com.woniuxy.openfeign.service.MyInfo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
 
@RestController
public class TestController {
 
 
    @Resource
    MyInfo myInfo;
 
    @GetMapping("/test")
    public String getTest() {
 
        System.out.println("test-openfeign");
        String result=myInfo.getUser();
        System.out.println(result);
        return result;
    }
 
    @GetMapping("/test1")
    public String getTest1() {
 
        return "test1";
    }
}

5启动项目

访问 url http://localhost:8085/test