前言
springcloud 反对两种客户端调用工具:
- RestTemplate,基本上不应用
- Feign,采纳接口加注解形式,可读性较强
注:本來打算持续应用 consul
作为注册核心来进行 Feign
客户端调用的,provide
配置如下,无奈始终调用不到 注册上来的服务名,只好改用 Eureka
来应用,如有晓得起因请指教!
##服务端口号server: port: 8501spring: application: ##服务别名--服务注册到consul名称 name: consul-member ##注册核心consul地址 cloud: consul: host: localhost port: 8500 discovery: service-name: ${spring.application.name} # 服务提供名称# ## consul ip地址# hostname: 192.168.3.91
Eureka Feign客户端调用
这里咱们基于 SpringCloud整合之Eureka高可用集群 我的项目来展现。provide
咱们不须要做任何批改,只须要在 consumer
order模块退出以下依赖:
<!--springcloud 整合openfeign--><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
feign 调用接口
MemberApiFeign.java
: @FeignClient指定provide服务别名,接口copy调用接口即可:
package com.baba.wlb.api.feign;import org.springframework.cloud.openfeign.FeignClient;import org.springframework.web.bind.annotation.RequestMapping;/** * @Author wulongbo * @Date 2021/1/21 19:17 * @Version 1.0 */@FeignClient(name = "app-member")public interface MemberApiFeign { // Feign 书写形式以springMVC接口模式书写 // @FeignClient调用服务接口name就是服务名称 @RequestMapping("/getMember") String getMember();}
管制页面
AppFeignController.java
: 注入 Feign 接口
package com.baba.wlb.api.controller;import com.baba.wlb.api.feign.MemberApiFeign;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * @Author wulongbo * @Date 2021/1/21 19:21 * @Version 1.0 */@RestControllerpublic class AppFeignController { @Autowired private MemberApiFeign memberApiFeign; @RequestMapping("/getFeignOrder") public String getFeignOrder() { return memberApiFeign.getMember(); }}
启动类
AppOrder
启动类:增加 @EnableFeignClients 开启Feign客户端权限
package com.baba.wlb;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.client.loadbalancer.LoadBalanced;import org.springframework.cloud.openfeign.EnableFeignClients;import org.springframework.context.annotation.Bean;import org.springframework.web.client.RestTemplate;/** * @Author wulongbo * @Date 2021/1/9 15:39 * @Version 1.0 */@SpringBootApplication@EnableDiscoveryClient@EnableFeignClientspublic class AppOrder { public static void main(String[] args) { SpringApplication.run(AppOrder.class, args); // 第二种形式 如果应用rest形式以别名形式进行调用依赖ribbon负载均衡器 // 第二种形式 @LoadBalanced能让restTemplate 模板在申请时领有客户端负载平衡的能力 } // 解决RestTemplate 找不到起因, 把RestTemplate注册到Springboot容器中 @Bean // 第一种形式// @Bean// RestTemplate restTemplate(){// return new RestTemplate();// } // 第二种形式 @LoadBalanced能让restTemplate 模板在申请时领有客户端负载平衡的能力// @Bean// @LoadBalanced// RestTemplate restTemplate() {// return new RestTemplate();// } // @EnableFeignClients 开启Feign客户端权限}
注:启动类地位要放正确
启动 Eureka Server服务,启动 member provide 服务,启动 order consumer 服务后拜访:http://localhost:8200/getFeignOrder