javascript
feign调用soap_Spring Cloud 组件 —— feign
feign 作為一個(gè)聲明式的 Http Client 開(kāi)源項(xiàng)目。在微服務(wù)領(lǐng)域,相比于傳統(tǒng)的 apache httpclient 與在 spring 中較為活躍的 RestTemplate 更面向服務(wù)化,更易于使用。底層封裝了?Jersey 與?CXF 分別用于 REsT 與?SOAP 的服務(wù)(對(duì)應(yīng)有 JAX-RS 與 JAX-WS? API),當(dāng)然也可以配置換成其它類(lèi)似的實(shí)現(xiàn),比如?OkHttp 、Ribbon 或者 Apache HC 等。
feign 基本用法及注解的使用看官方文檔。下面介紹下 Spring Cloud 中的封裝及實(shí)現(xiàn)細(xì)節(jié)(Spring Cloud?文檔):
一、 基本用法
現(xiàn)有服務(wù)提供方:需要調(diào)用它的 createUser 方法
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/current", method = RequestMethod.GET)
public Principal getUser(Principal principal) {
return principal;
}
@PreAuthorize("#oauth2.hasScope('server')")
@RequestMapping(method = RequestMethod.POST)
public void createUser(@Valid @RequestBody User user) {
userService.create(user);
}
}
使用 feign 構(gòu)建消費(fèi)服務(wù)方,遵循以下步驟:
引入 maven 依賴(lài)
org.springframework.cloud
spring-cloud-starter-openfeign
1. 啟用:使用??@EnableFeignClients注解啟動(dòng) feign 模塊基礎(chǔ)功能(掃描 feign client包,使用默認(rèn)或指定的相關(guān)配置等等)
@SpringBootApplication
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2. 聲明:使用@FeignClient("app-name")創(chuàng)建聲明式的 HC:很簡(jiǎn)單配置下 service 名稱(chēng)/url 與 發(fā)出請(qǐng)求的路徑就好了。
@FeignClient(name = "auth-service")
public interface AuthServiceClient {
@RequestMapping(method = RequestMethod.POST, value = "/users", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
void createUser(User user);
}
3. 調(diào)用:上面的代碼,相對(duì)于服務(wù)提供方,它是客戶(hù)端服務(wù)消費(fèi)方。相對(duì)于服務(wù)消費(fèi)方自身,它上升到一個(gè) service,因此我們可以在 service 層或 controller 層調(diào)用它:
@Service
public class AccountServiceImpl implements AccountService {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private AuthServiceClient authClient;
@Autowired
private AccountRepository repository;
/**
* {@inheritDoc}
*/
@Override
public Account create(User user) {
Account existing = repository.findByName(user.getUsername());
Assert.isNull(existing, "account already exists: " + user.getUsername());
// 調(diào)用feign HC服務(wù)
authClient.createUser(user);
Saving saving = new Saving();
saving.setAmount(new BigDecimal(0));
saving.setCurrency(Currency.getDefault());
saving.setInterest(new BigDecimal(0));
saving.setDeposit(false);
saving.setCapitalization(false);
Account account = new Account();
account.setName(user.getUsername());
account.setLastSeen(new Date());
account.setSaving(saving);
repository.save(account);
log.info("new account has been created: " + account.getName());
return account;
}
...
二、feign 的相關(guān)配置(比如日志、hytrix? 等)
配置方式有 3種:
1. 使用 JavaConfig 方式
配置類(lèi)(這里建議不要加 @Configuration 注解,否則將變成全局配置)
public class FileConf {
private final ObjectFactory messageConverters;
@Autowired
public FileConf(ObjectFactory messageConverters) {
this.messageConverters = messageConverters;
}
@Bean
public Encoder feignFormEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
}
調(diào)用端
@FeignClient(value = "service-thirdparty", configuration = FileConf.class)
@RequestMapping(value = "/storage")
public interface StorageClient {
/**
* 上傳圖片
*/
@RequestMapping(
value = "/imageUpload",
method = RequestMethod.POST,
consumes = MULTIPART_FORM_DATA_VALUE)
BusinessResult uploadImage(@RequestParam(value = "bucket") String bucket,
@RequestPart(value = "file", required = false) MultipartFile file);
2. 使用 application.yml
# To disable Hystrix in Feign
feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: basic
hystrix:
enabled: false
# To set thread isolation to SEMAPHORE
hystrix:
command:
default:
execution:
isolation:
strategy: SEMAPHORE
logging.level.project.user.UserClient: DEBUG
注意事項(xiàng):
① 如果 @Configuration的 JavaConfig 與 properties 配置同時(shí)存在,那么后者會(huì)覆蓋前者。通過(guò)設(shè)定?feign.client.default-to-properties?to?false. 改變優(yōu)先權(quán)。
② 只有開(kāi)啟 DEBUG級(jí)別的日志, feign 的log功能才會(huì)生效。
③ 如果 classpath 引入了 hytrix(如下),并且配置啟用 hytrix(比如 ?feign.hystrix.enabled=true),那么默認(rèn)會(huì)啟用?circuit breaker 。
org.springframework.cloud
spring-cloud-starter-netflix-hystrix
在 Spring Cloud Dalston 及之后的版本中,circuit breaker 是可選操作。需要使用?@EnableCircuitBreaker 手動(dòng)開(kāi)啟。
@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class Application {
擴(kuò)展:使用斷路器功能
聲明:
@FeignClient(name = "statistics-service", fallback = StatisticsServiceClientFallback.class)
public interface StatisticsServiceClient {
@RequestMapping(method = RequestMethod.PUT, value = "/statistics/{accountName}", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
void updateStatistics(@PathVariable("accountName") String accountName, Account account);
}
定義 hytrix:
@Component
public class StatisticsServiceClientFallback implements StatisticsServiceClient {
private static final Logger LOGGER = LoggerFactory.getLogger(StatisticsServiceClientFallback.class);
@Override
public void updateStatistics(String accountName, Account account) {
LOGGER.error("Error during update statistics for account: {}", accountName);
}
}
233
參考資料
https://github.com/sqshq/PiggyMetrics (完整示例)
總結(jié)
以上是生活随笔為你收集整理的feign调用soap_Spring Cloud 组件 —— feign的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: mfc static 文本自适应宽度_基
- 下一篇: use vue 多个_vue.use 插