springCloud提供的微服务接口调用有 Ribbon+RestTemplate和feign两种,Feign是一种负载均衡的HTTP客户端, 使用Feign调用API就像调用本地方法一样,从避免了调用目标微服务时,需要不断的解析/封装json 数据的繁琐。Feign集成了Ribbon。Ribbon+eureka是面向微服务编程,而Feign是面向接口编程。Feign同样具有负载均衡功能。
项目demo构建参考:https://blog.csdn.net/f123147/article/details/115904274
在Ppom文件中假如Feign的依赖
<!-- 微服务组件-feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>${spring.cloud.netflix.version}</version>
</dependency>
在前端front工程启动类上写上@EnableFeignClients注解
package com.gmf.briup;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
public class FrontApplication {
public static void main(String[] args) {
SpringApplication.run(FrontApplication.class, args);
}
}
在前端front工程中service层创建接口
package com.gmf.briup.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/*
* 这是一个接口,Feign会通过动态代理,帮我们生成实现类
*/
@FeignClient(value = "order-service") //调用哪个微服务
public interface FeignService {
@ResponseBody
@RequestMapping("/orderService/service/getPort")
String getPort();
}
在前端接口front工程web层创建对外暴露的接口
package com.gmf.briup.controller;
import com.gmf.briup.service.FeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/feign")
public class FeignController {
@Autowired
FeignService feignService;
@ResponseBody
@RequestMapping(value = "/getOrderServicePort")
public String sayHi(){
//调用service层的方法,该方法和order-service微服务的接口绑定在一起
String port = feignService.getPort();
System.out.println(port);
return port;
}
}
在浏览器中输入front工程对外暴露的接口:http://127.0.0.1:8090/feign/getOrderServicePort
结果如下
从这里可以看出,Feign的负载均衡算法默认也是轮询。