SpringCloud:服务调用——自定义Feign方式实现

2024-06-21 02:48

本文主要是介绍SpringCloud:服务调用——自定义Feign方式实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一,SpringCloud 服务调用

    Spring Cloud提供了两种方式进行服务调用,分别为RestTemplate方式和声明式Feign方式,两种代用方式在 SpringCloud:注册中心——Eureka中已经进行了演示;本篇文章参考Feign方式,整合RestTemplate实现自定义的声明式Feign调用

二,步骤解析

    1,搭建简易声明式Feign客户端调动环境,并初步调通

    2,重写@EnableFeignClients -> @EnableRestFeign,引用注册类为下面自定义注册类

    3,重写@FeignClient -> @RestClient

    4,重写注册类 -> RestFeignRegisters,通过JDK动态代理获取被@RestClient注解接口的代理对象,并通过BeanDeifinition注册到Spring Bean容器

    5,重写JDK动态代理需要的InvocationHandler方法 -> MyInvocationHandler,拼接访问URL后,通过RestTemplate进行调用

三,调用流程

    1,启动服务时:

        @EnableRestFeign -> RestFeignRegisters :注册被@RestClient注解的接口代理对象到SpringBean容器中

    2,服务调用时:

        * 通过调用的接口路径@RequestMapping及参数@RequestParam拼接服务访问路径 http://{serviceName}/{uri}?{param}

        * 拼接成功后,通过RestTemplate直接进行服务调用

四,服务端代码

    * 接口 -> com-gupao-springcloud-selffeign-server-api

package com.gupao.self.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;/*** @author pj_zhang* @create 2019-01-24 0:38**/
public interface ISelfFeignController {@RequestMapping("/getMessage")String getMessage(@RequestParam("message") String message);
}

    * 实现类 -> com-guapo-springcloud-selffeign-server

package com.gupao.self.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;/*** @author pj_zhang* @create 2019-01-24 0:30**/
@RestController
public class SelfFeignController implements ISelfFeignController {@Override@RequestMapping("/getMessage")public String getMessage(@RequestParam("message") String message) {return "SelfFeignController.getMessage : " + message;}}

五,代码实现

    1,搭建简易声明式Feign客户端调动环境,并初步调通

        * 项目架构,具体方式参考博文SpringCloud:注册中心——Eureka

        * 客户端自定义Feign结构

    2,重写@EnableFeignClients -> @EnableRestFeign

package com.gupao.self.feign.annotation;import com.gupao.self.feign.register.RestFeignRegisters;
import org.springframework.context.annotation.Import;import java.lang.annotation.*;/*** @author pj_zhang* @create 2019-01-23 23:01**/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({RestFeignRegisters.class})
public @interface EnableRestFeign {/*** 指定RestClient端口* @return*/Class<?>[] clients() default {};}

    3,重写@FeignClient -> @RestClient

package com.gupao.self.feign.annotation;import java.lang.annotation.*;/*** @author pj_zhang* @create 2019-01-23 23:08**/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RestClient {String name() default "";
}

    4,重写注册类 -> RestFeignRegisters,通过JDK动态代理获取被@RestClient注解接口的代理对象,并通过BeanDeifinition注册到Spring Bean容器

package com.gupao.self.feign.register;import com.gupao.self.feign.annotation.EnableRestFeign;
import com.gupao.self.feign.annotation.RestClient;
import com.gupao.self.feign.handler.MyInvocationHandler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.SingletonBeanRegistry;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.type.AnnotationMetadata;import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.stream.Stream;/*** @author pj_zhang* @create 2019-01-23 23:01**/
public class RestFeignRegisters implements ImportBeanDefinitionRegistrar, BeanFactoryAware {private BeanFactory beanFactory;@Overridepublic void registerBeanDefinitions(AnnotationMetadata annotationMetadata,BeanDefinitionRegistry registry) {// 获取@EnableRestFeign模块引用的需要注册的Class类Map<String, Object> attributes =annotationMetadata.getAnnotationAttributes(EnableRestFeign.class.getName());Class<?>[] classes = (Class<?>[]) attributes.get("clients");// 筛选所有被Feign客户端注解的类, @RestFeignStream.of(classes)// 过滤接口.filter(Class::isInterface)// 仅选择标注了@RestClient注解的接口.filter(interfaceClass ->AnnotationUtils.findAnnotation(interfaceClass, RestClient.class) != null)// 过滤requestMapping方法.forEach(restClientClass -> {// 通过@RestClient源数据获取应用名称RestClient restClient =AnnotationUtils.findAnnotation(restClientClass, RestClient.class);String serverName = restClient.name();// @RestClient注解类进行动态代理Object proxy = Proxy.newProxyInstance(registry.getClass().getClassLoader(),new Class[]{restClientClass},new MyInvocationHandler(serverName, beanFactory));// 将@RestClient接口代理实现proxy注册为BeanString beanName = "RestClient." + serverName;// 通过SingletonBeanRegistry注册bean
//                    if (registry instanceof SingletonBeanRegistry) {
//                        SingletonBeanRegistry singletonBeanRegistry = (SingletonBeanRegistry) registry;
//                        singletonBeanRegistry.registerSingleton(serverName, proxy);
//                    }// 通过BeanDefinition注册BeanBeanDefinitionBuilder beanDefinitionBuilder =BeanDefinitionBuilder.genericBeanDefinition(RestClientClassFactoryBean.class);beanDefinitionBuilder.addConstructorArgValue(restClientClass);beanDefinitionBuilder.addConstructorArgValue(proxy);BeanDefinition beanDefinition = beanDefinitionBuilder.getRawBeanDefinition();registry.registerBeanDefinition(beanName, beanDefinition);});}/*** 自定义FactoryBean类,* 通过BeanDefinition方式注册类到Spring Bean容器中*/private static class RestClientClassFactoryBean implements FactoryBean {private final Class<?> restClient;private final Object proxy;private RestClientClassFactoryBean(Class<?> restClient, Object proxy) {this.restClient = restClient;this.proxy = proxy;}@Overridepublic Object getObject() throws Exception {return proxy;}@Overridepublic Class<?> getObjectType() {return restClient;}}/*** 通过集成BeanFactoryWare获取Spring Bean容器* 在通过RestTemplate进行方法调用时, 获取RestTemplate* @param beanFactory* @throws BeansException*/@Overridepublic void setBeanFactory(BeanFactory beanFactory) throws BeansException {this.beanFactory = beanFactory;}
}

    5,重写JDK动态代理需要的InvocationHandler方法 -> MyInvocationHandler,拼接访问URL后,通过RestTemplate进行调用

package com.gupao.self.feign.handler;import org.springframework.beans.factory.BeanFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;/*** @author pj_zhang* @create 2019-01-23 23:26**/
public class MyInvocationHandler implements InvocationHandler {// ServiceNameprivate final String serviceName;private final BeanFactory beanFactory;public MyInvocationHandler(String serviceName, BeanFactory beanFactory) {this.serviceName = serviceName;this.beanFactory = beanFactory;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {// 通过RestTemplate进行调用, 进行拼接访问路径, 访问路径参数如下// http://servierName/uri?param// 此处需要获取三个参数, 分别为// serviceName 从register获取// url 从方法注解获取RequestMapping requestMapping = AnnotationUtils.getAnnotation(method, RequestMapping.class);String[] uri = requestMapping.value();// param// 获取方法参数数量int count = method.getParameterCount();// 获取方法参数类型集合Class<?>[] parameterTypes = method.getParameterTypes();StringBuilder sb = new StringBuilder();for (int i = 0; i < count; i ++) {// 获取方法第i个参数注解Annotation[] annotations = method.getParameterAnnotations()[i];// 遍历注解, 获取参数名称String paramName = null;for (Annotation annotation : annotations) {if (annotation instanceof RequestParam) {paramName = ((RequestParam) annotation).value();break;}}String paramValue = String.valueOf(args[i]);// 拼接参数sb.append("&").append(paramName).append("=").append(paramValue);}// 拼接完整URL// http://servierName/uri?paramStringBuilder acturalUrl = new StringBuilder();acturalUrl.append("http://").append(serviceName).append("/").append(uri[0]).append("?").append(sb.toString());// 从BeanFactory容器中获取RestTemplate, 进行执行RestTemplate restTemplate = beanFactory.getBean("restTemplate", RestTemplate.class);return restTemplate.getForObject(acturalUrl.toString(), String.class);}
}

    6,feign接口 -> 注意@FeignClient注解替换为@RestFeign

package com.gupao.self.feign;import com.gupao.self.controller.ISelfFeignController;
import com.gupao.self.feign.annotation.RestClient;
import org.springframework.cloud.openfeign.FeignClient;/*** @author pj_zhang* @create 2019-01-24 0:42**/
@RestClient(name = "server-feign")
public interface ISelfFeign extends ISelfFeignController {
}

    7,启动类 -> 注意@EnableFeignClients替换为@EnableRestFeign

package com.gupao;import com.gupao.self.feign.ISelfFeign;
import com.gupao.self.feign.annotation.EnableRestFeign;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;/*** @author pj_zhang* @create 2019-01-24 0:34**/
@SpringBootApplication
//@EnableFeignClients
@EnableRestFeign(clients = ISelfFeign.class)
@EnableEurekaClient
public class SelfFeignClientApp {public static void main(String[] args) {SpringApplication.run(SelfFeignClientApp.class, args);}@LoadBalanced@Beanpublic RestTemplate restTemplate() {return new RestTemplate();}}

    8,调用结果

这篇关于SpringCloud:服务调用——自定义Feign方式实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1080003

相关文章

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

MySQL中查找重复值的实现

《MySQL中查找重复值的实现》查找重复值是一项常见需求,比如在数据清理、数据分析、数据质量检查等场景下,我们常常需要找出表中某列或多列的重复值,具有一定的参考价值,感兴趣的可以了解一下... 目录技术背景实现步骤方法一:使用GROUP BY和HAVING子句方法二:仅返回重复值方法三:返回完整记录方法四:

IDEA中新建/切换Git分支的实现步骤

《IDEA中新建/切换Git分支的实现步骤》本文主要介绍了IDEA中新建/切换Git分支的实现步骤,通过菜单创建新分支并选择是否切换,创建后在Git详情或右键Checkout中切换分支,感兴趣的可以了... 前提:项目已被Git托管1、点击上方栏Git->NewBrancjsh...2、输入新的分支的

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

Java进程异常故障定位及排查过程

《Java进程异常故障定位及排查过程》:本文主要介绍Java进程异常故障定位及排查过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、故障发现与初步判断1. 监控系统告警2. 日志初步分析二、核心排查工具与步骤1. 进程状态检查2. CPU 飙升问题3. 内存

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

java中新生代和老生代的关系说明

《java中新生代和老生代的关系说明》:本文主要介绍java中新生代和老生代的关系说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、内存区域划分新生代老年代二、对象生命周期与晋升流程三、新生代与老年代的协作机制1. 跨代引用处理2. 动态年龄判定3. 空间分

Java设计模式---迭代器模式(Iterator)解读

《Java设计模式---迭代器模式(Iterator)解读》:本文主要介绍Java设计模式---迭代器模式(Iterator),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录1、迭代器(Iterator)1.1、结构1.2、常用方法1.3、本质1、解耦集合与遍历逻辑2、统一