自定義注解簡單實作類似Feign的功能
- 最近在玩spring源碼,上文 spring自定義元件掃描,模仿@MapperScan 利用spring的beanFactoryProcessor進行掃描注冊,最後結合jdbc完成簡單封裝。
- feign的源碼怎麼樣子我沒看過,隻知道基于http調用(本文暫未內建配置中心)
- 本文内容深度依賴于spring。
涉及主要知識點:
- spring的BeanPostProcessor後置處理器
- jdk動态代理
- restTemplate進行http請求
1.注解定義
@EnableRemoteClient 開啟,對比一下@EnableFeignClients
/**
* 開啟http遠端調用,為什麼叫rpc,因為本項目要結合dubbo一起使用
* @author authorZhao
* @date 2019/12/20
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(RpcInstantiationAwareBeanPostProcessor.class)//這個類重點注意
public @interface EnableRemoteClient {
}
@RpcClient 對比一下@FeignClient
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RpcClient {
/**
* 服務在注冊中心的名稱,暫未內建配置中心,預計使用nacos
* @return
*/
String value() default "";
/**
* url字首,通路的url字首,如果沒有注冊中心這個路徑代表通路的url字首
* @return
*/
String URLPre() default "";
/**
* 調用方式包括http、rpc
* @return
*/
String cllType() default "";
}
[email protected] 注解的解析
說明:本文采用beanPostProcessor形式進行bean的代理生成,不采用上篇文章的beanFactoryPosrProcessor進行注冊,目的是為了了解springaop的實作.
BeanPostProcessor的功能
- 在bean執行個體化前後執行一些事情,類似自己的初始化和銷毀方法
- BeanPostProcessor有一個子接口的執行時機和一般的不一樣,InstantiationAwareBeanPostProcessor 接口實在bean建立之前執行,aop這篇先不多說
spring源碼分析
- finishBeanFactoryInitialization(beanFactory);spring建立bean的方法,不清楚的可以看看spring的refresh()方法
try {
//在創bean執行個體化之前給一個後置處理器傳回代理對象的機會,這裡就是操作的地方
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.//給後置處理器一個機會傳回一個目标代理對象
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
spring的分析暫時結束
RpcInstantiationAwareBeanPostProcessor 的作用
- RpcInstantiationAwareBeanPostProcessor 重寫了postProcessBeforeInstantiation方法,就是上面spring源碼需要重寫的方法
- 為什麼實作ApplicationContextAware ,我用來檢測本地有沒有注冊自己的接口定義,不然代理不到,debug用的,可以不用實作
/**
* @author authorZhao
* @date 2019/12/20
*/
@Slf4j
public class RpcInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor , ApplicationContextAware {
private ApplicationContext applicationContext;
/**
* 執行個體化前,後面的方法可以不用看了
* @param beanClass
* @param beanName
* @return
* @throws BeansException
*/
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
log.info("正在為:{}生成代理對象,被代理的類為:{}",beanName,beanClass.getName());
//檢測需要執行個體化的bean有沒有@RpcClient注解,有的話進行代理,沒有傳回null就行
RpcClient rpcClient = AnnotationUtil.getAnnotation(beanClass, RpcClient.class);
if (rpcClient == null) return null;
//動态代理裡面需要實作的方法,本文采用的是jdk動态代理
Supplier<ProxyMethod<Object, Method, Object[], Object>> supplier = RpcMethodImpl::httpRemote;
//傳回代理對象
Object object = ProxyUtil.getObject(beanClass, supplier.get());
return object;
}
/**
* 執行個體化後
* @param bean
* @param beanName
* @return
* @throws BeansException
*/
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
return true;
}
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
return pvs;
}
/**
* 初始化錢
* @param bean
* @param beanName
* @return
* @throws BeansException
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
/**
* 初始化後
* @param bean
* @param beanName
* @return
* @throws BeansException
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext=applicationContext;
}
}
@RequestMapping的解析
- 已經深度使用spring了,就直接利用spring的注解
使用方式
//使用案例如下
@RpcClient(URLPre="http://localhost:8099/menu")
public interface MenuService {
@PostMapping("/getMenuByQuery")
ApiResult getMenuByQuery();
@GetMapping("/getMenuByRoleId")
ApiResult getMenuByRoleId(@PathVariable String roleId);
}
代理方法
//這個就是jdk的動态代理所需要實作的方法,不熟悉的看作者上一篇文章即可
public static ProxyMethod<Object, Method,Object[],Object> httpRemote() {
ProxyMethod<Object, Method,Object[],Object> cgLibProxyMethod =
(proxy,method,args)->{
//1.決定請求方式
String methodName = method.getName();
String url = "";
//2.得到請求路徑
RpcClient annotationImpl = AnnotationUtil.getAnnotationImpl(proxy.getClass(), RpcClient.class);//這裡的AnnotationUtil是自己寫的,簡單擷取注解,後面帶s的是spring的可以獲得元注解資訊
if(annotationImpl!=null)url = annotationImpl.URLPre();
HttpMapping requestMapping = getRequestMapping(method);//HttpMapping用于統一GetMapping、PostMapping、RequestMapping的
//@RpcClient 的請求字首
String urlFix = requestMapping.getValue();
if(StringUtils.isBlank(urlFix)){
//如果沒寫,預設将方法名作為路徑
url = url+"/"+methodName;
}else{
url = url +urlFix;
}
//3.執行http請求
return doHttp(url,method,args, requestMapping.getHttpMethod());
};
return cgLibProxyMethod;
}
dohttp
private static Object doHttp(String url, Method method, Object[] args, HttpMethod httpMethod) {
//1.restTemplate建構
RestTemplate restTemplate = new RestTemplate();
//2.請求頭與請求類型
//這個執行了兩次,暫時未調整
HttpMapping httpMapping = getRequestMapping(method);
//1.獲得請求頭
HttpHeaders headers = getHeader(); // http請求頭
List<MediaType> mediaTypeList = new ArrayList<>();
mediaTypeList.add(MediaType.APPLICATION_JSON_UTF8);
//content-type的設定,預設json+u8,畢竟背景接口傳回的都是json
//2.設定consumer
String[] consumes = httpMapping.getConsumes();
if(consumes!=null&&consumes.length>0)headers.setContentType(MediaType.parseMediaType(consumes[0]));
String[] produces = httpMapping.getProduces();
if(produces!=null&&produces.length>0)mediaTypeList.add(MediaType.parseMediaType(produces[0]));
headers.setAccept(mediaTypeList);
MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
Map<String, Object> map = new HashMap<>();
//重點注解解析
//支援三個注解,不要亂用
//1.PathVariable,将帶有這個注解的放在url上面,這列采用手工操作
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
if(parameter==null)continue;
String paramname = parameter.getName();
PathVariable pathVariable = parameter.getAnnotation(PathVariable.class);
if(pathVariable!=null){
//為空會報錯
url = url +"/"+args[i].toString();
}
//@RequestParam的value作為http請求參數的key,如果沒有采用方法的參數名,注意方法的參數名沒做處理可能會是args0等
RequestParam requestParam = parameter.getAnnotation(RequestParam.class);
if(requestParam!=null){
String name = requestParam.value();
paramname = StringUtils.isNotBlank(name)?name:paramname;
}
if(args[i]!=null){
form.add(paramname,(args[i]));
}
}
//@RequestBody,如果帶有這個注解的話将所有非url參數轉化為json
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
RequestBody requestBody = parameter.getAnnotation(RequestBody.class);
if(requestBody!=null){
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//帶有requestBody時候全體當做一個參數打包成json
String json = JSON.toJSONString(form);
log.error("正在發送json形式的請求,請求資料為:{}",json);
HttpEntity<String> httpEntity = new HttpEntity<>(json, headers);
return httpEntity;
}
}
//2.RequestBody
//3.PathVariable
//RequestParam,
//RequestBody,
//PathVariable
//3.設定參數
//普通post
//json
//headers.setContentType(MediaType.APPLICATION_JSON_UTF8); // 請求頭設定屬性
//headers.setContentType(MediaType.parseMediaType("multipart/form-data; charset=UTF-8"));
//
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(form, headers);
//3.參數解析
//4.結果傳回
Class<?> returnType = method.getReturnType();
//背景接收的位址
//String url = "http://localhost:8092/process/saveProcess";
log.info("正發起http請求,url={},請求參數={}",url,httpEntity.getBody().toString());
//restTemplate.postForEntity()
ResponseEntity result = restTemplate.exchange(url, httpMethod, httpEntity, returnType);
log.info("http請求結果為{}", JSON.toJSONString(result.getBody()));
log.info("http請求結果為{}", JSON.toJSONString(result.getBody()));
return result.getBody();
}
測試
1.啟動類
@SpringBootApplication
@ComponentScan({"com.git.file","com.git.gateway.controller","com.git.gateway.service"})//掃描
@MapperScan("com.git.file.mapper")
@EnableRemoteClient//開啟http代理
@Import({TestService.class,ArticleService.class, MenuService.class})//接口注冊,注意接口上面加@Services的時候spring不不會注冊這個bean定義的
2.controller,消費者,我這裡是網關的
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private TestService testService;
@Autowired
private ArticleService articleService;
@Autowired
private MenuService menuService;
@RequestMapping("/getById/{id}")
public ApiResult getById(@PathVariable String id){
return testService.getById(id);
}
@RequestMapping("/read/{id}")
public ApiResult read(@PathVariable String id){
return articleService.getById(id);
}
@RequestMapping("/getMenuByQuery")
public ApiResult getMenuByQuery(){
return menuService.getMenuByQuery();
}
@RequestMapping("/getMenuByRoleId/{id}")
public ApiResult getMenuByRoleId(@PathVariable String id){
return menuService.getMenuByRoleId(id);
}
}
3.service
這個就不全部列出來了,其中json的還未測試
/**
* @author authorZhao
* @date 2019/12/20
*/
@RpcClient(URLPre="http://localhost:8099/menu")
public interface MenuService {
@PostMapping("/getMenuByQuery")
ApiResult getMenuByQuery();
@GetMapping("/getMenuByRoleId")
ApiResult getMenuByRoleId(@PathVariable String roleId);
}
4.啟動另一個服務提供接口
這裡不展示了
5.效果圖
1.網管的截圖
2.員服務直接調用的
3.網關的日志
結束
1.說明
- 本文還有很多方法未實作
- 本文的注解工具類一個是自己寫的,一個是spring的,spring的帶s,并且可以獲得元注解,這個很重要
- 本文還未實作與注冊中心的對接
-
本文為貼出來的代碼暫時沒有公開有不了解的直接留言即可,作者還在繼續學習繼續完善中
2.打碼感想
- 雖然沒有看feign的源碼們現在也基本猜到怎麼實作的了,不包括注冊中心和負載均衡等等元件
- 對spring注冊bean和創房bean的認識進一步加深
本文為作者原創,轉載請申明