本文是 极客时间 杨波 《Spring Boot 与 Kubernetes 云原生微服务实践》 的学习笔记。如果对原课程有兴趣,欢迎扫码订阅(见文章末尾)
文章目录
强类型客户端
- Response 不可使用泛型,泛型在运行期信息会被擦除
- 使用Response 里边的code表示状态码,如果用Http status code表示,支持强类型客户端会更复杂
Spring Feign
Demo
@FeignClient(name = "account-service", path = "/v1/account", url = "${staffjoy.account-service-endpoint}")
// TODO Client side validation can be enabled as needed
// @Validated
public interface AccountClient {
@PostMapping(path = "/create")
GenericAccountResponse createAccount(@RequestHeader(AuthConstant.AUTHORIZATION_HEADER) String authz, @RequestBody @Valid CreateAccountRequest request);
}
- AccountController in account-svc
@RestController
@RequestMapping("/v1/account")
@Validated
public class AccountController {
@PostMapping(path = "/create")
@Authorize(value = {
AuthConstant.AUTHORIZATION_SUPPORT_USER,
AuthConstant.AUTHORIZATION_WWW_SERVICE,
AuthConstant.AUTHORIZATION_COMPANY_SERVICE
})
public GenericAccountResponse createAccount(@RequestBody @Valid CreateAccountRequest request) {
AccountDto accountDto = accountService.create(request.getName(), request.getEmail(), request.getPhoneNumber());
GenericAccountResponse genericAccountResponse = new GenericAccountResponse(accountDto);
return genericAccountResponse;
}
}
数据校验
@Documented
@Constraint(validatedBy = PhoneNumberValidator.class)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface PhoneNumber {
String message() default "Invalid phone number";
Class[] groups() default {};
Class[] payload() default {};
}
public class PhoneNumberValidator implements ConstraintValidator<PhoneNumber, String> {
@Override
public boolean isValid(String phoneField, ConstraintValidatorContext context) {
if (phoneField == null) return true; // can be null
return phoneField != null && phoneField.matches("[0-9]+")
&& (phoneField.length() > 8) && (phoneField.length() < 14);
}
}