說明:兩種方式,演示
(1) 同一個interface中調用多個服務的接口(RequestLine)
(2)同一個interface調用一個服務的接口(ReqMapping)
一 、準備
<!-- Feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<!-- netflix 熔斷器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
配置類:
@Configuration
public class FeignConfig {
@Bean
public Contract feignContract() {
return new feign.Contract.Default();
}
/**
* 注入Bean 方便後續使用
*
* @return
*/
@Bean
public Feign.Builder a() {
return Feign.builder()
.decoder(new JacksonDecoder())
.options(new Request.Options(1000, 3500))
.retryer(new Retryer.Default(5000, 5000, 3));
}
}
啓動類:
啓動類上開啓Feign
@EnableFeignClients
配置文件開啓熔斷器(不適用熔斷也可以,只是調用失敗之後錯誤自己處理)
@Component
public class FallBack implements RemoteAction {
@Override
public Map loginAction(String username, String password) {
return new HashMap<String,Object>(){{
put("msg","失敗");
}};
}
}
二、service(interface)
第一種方式:
/**
* 通用接口,
* 因爲的調用目標服務的IP、和端口會傳遞過來
*/
@FeignClient(name = "provider", fallback = FallBack.class, configuration = FeignConfig.class)
public interface RemoteAction {
@RequestLine("GET /cdn/a/")
Map loginAction(@Param("username") String username,
@Param("password") String password);
}
Controller:
@Autowired
Feign.Builder builder;
/**
* RequestLine 方式
*/
@RequestMapping("test")
public void tt() {
RemoteAction action = builder.target(RemoteAction.class,"http://127.0.0.1:88/");
System.out.println( action.loginAction("用戶名","密碼"));
}
第二種方式:
/**
* =================================================================================================================================
* 針對某個特定服務
* 固定調用某個服務,
* 本接口只能調用 http://127.0.0.1:88 下的action
*/
@FeignClient(name = "provider2", url = "http://127.0.0.1:88", fallback = FallBack2.class, configuration = FeignConfig.class)
public interface RemoteAction2 {
@RequestMapping(value = "/a/", method = RequestMethod.GET)
Map loginAction();
}
Controller:
@Autowired
RemoteAction2 remoteAction2;
/**
* desc:
* param: @RequestMapping 方式
* author: CDN
* date: 2020-5-25
*/
@RequestMapping("twst2")
public void test2(){
Map map = remoteAction2.loginAction();
}