javascript
feign调用soap_Spring Cloud 组件 —— feign
feign 作為一個聲明式的 Http Client 開源項目。在微服務領域,相比于傳統的 apache httpclient 與在 spring 中較為活躍的 RestTemplate 更面向服務化,更易于使用。底層封裝了?Jersey 與?CXF 分別用于 REsT 與?SOAP 的服務(對應有 JAX-RS 與 JAX-WS? API),當然也可以配置換成其它類似的實現,比如?OkHttp 、Ribbon 或者 Apache HC 等。
feign 基本用法及注解的使用看官方文檔。下面介紹下 Spring Cloud 中的封裝及實現細節(Spring Cloud?文檔):
一、 基本用法
現有服務提供方:需要調用它的 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 構建消費服務方,遵循以下步驟:
引入 maven 依賴
org.springframework.cloud
spring-cloud-starter-openfeign
1. 啟用:使用??@EnableFeignClients注解啟動 feign 模塊基礎功能(掃描 feign client包,使用默認或指定的相關配置等等)
@SpringBootApplication
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2. 聲明:使用@FeignClient("app-name")創建聲明式的 HC:很簡單配置下 service 名稱/url 與 發出請求的路徑就好了。
@FeignClient(name = "auth-service")
public interface AuthServiceClient {
@RequestMapping(method = RequestMethod.POST, value = "/users", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
void createUser(User user);
}
3. 調用:上面的代碼,相對于服務提供方,它是客戶端服務消費方。相對于服務消費方自身,它上升到一個 service,因此我們可以在 service 層或 controller 層調用它:
@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());
// 調用feign HC服務
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 的相關配置(比如日志、hytrix? 等)
配置方式有 3種:
1. 使用 JavaConfig 方式
配置類(這里建議不要加 @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));
}
}
調用端
@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
注意事項:
① 如果 @Configuration的 JavaConfig 與 properties 配置同時存在,那么后者會覆蓋前者。通過設定?feign.client.default-to-properties?to?false. 改變優先權。
② 只有開啟 DEBUG級別的日志, feign 的log功能才會生效。
③ 如果 classpath 引入了 hytrix(如下),并且配置啟用 hytrix(比如 ?feign.hystrix.enabled=true),那么默認會啟用?circuit breaker 。
org.springframework.cloud
spring-cloud-starter-netflix-hystrix
在 Spring Cloud Dalston 及之后的版本中,circuit breaker 是可選操作。需要使用?@EnableCircuitBreaker 手動開啟。
@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class Application {
擴展:使用斷路器功能
聲明:
@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 (完整示例)
總結
以上是生活随笔為你收集整理的feign调用soap_Spring Cloud 组件 —— feign的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mfc static 文本自适应宽度_基
- 下一篇: gradle idea java ssm