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

相关文章

Python实现AVIF图片与其他图片格式间的批量转换

《Python实现AVIF图片与其他图片格式间的批量转换》这篇文章主要为大家详细介绍了如何使用Pillow库实现AVIF与其他格式的相互转换,即将AVIF转换为常见的格式,比如JPG或PNG,需要的小... 目录环境配置1.将单个 AVIF 图片转换为 JPG 和 PNG2.批量转换目录下所有 AVIF 图

Java Predicate接口定义详解

《JavaPredicate接口定义详解》Predicate是Java中的一个函数式接口,它代表一个判断逻辑,接收一个输入参数,返回一个布尔值,:本文主要介绍JavaPredicate接口的定义... 目录Java Predicate接口Java lamda表达式 Predicate<T>、BiFuncti

Pydantic中model_validator的实现

《Pydantic中model_validator的实现》本文主要介绍了Pydantic中model_validator的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价... 目录引言基础知识创建 Pydantic 模型使用 model_validator 装饰器高级用法mo

Spring Security基于数据库的ABAC属性权限模型实战开发教程

《SpringSecurity基于数据库的ABAC属性权限模型实战开发教程》:本文主要介绍SpringSecurity基于数据库的ABAC属性权限模型实战开发教程,本文给大家介绍的非常详细,对大... 目录1. 前言2. 权限决策依据RBACABAC综合对比3. 数据库表结构说明4. 实战开始5. MyBA

AJAX请求上传下载进度监控实现方式

《AJAX请求上传下载进度监控实现方式》在日常Web开发中,AJAX(AsynchronousJavaScriptandXML)被广泛用于异步请求数据,而无需刷新整个页面,:本文主要介绍AJAX请... 目录1. 前言2. 基于XMLHttpRequest的进度监控2.1 基础版文件上传监控2.2 增强版多

Spring Security方法级安全控制@PreAuthorize注解的灵活运用小结

《SpringSecurity方法级安全控制@PreAuthorize注解的灵活运用小结》本文将带着大家讲解@PreAuthorize注解的核心原理、SpEL表达式机制,并通过的示例代码演示如... 目录1. 前言2. @PreAuthorize 注解简介3. @PreAuthorize 核心原理解析拦截与

一文详解JavaScript中的fetch方法

《一文详解JavaScript中的fetch方法》fetch函数是一个用于在JavaScript中执行HTTP请求的现代API,它提供了一种更简洁、更强大的方式来处理网络请求,:本文主要介绍Jav... 目录前言什么是 fetch 方法基本语法简单的 GET 请求示例代码解释发送 POST 请求示例代码解释

Java图片压缩三种高效压缩方案详细解析

《Java图片压缩三种高效压缩方案详细解析》图片压缩通常涉及减少图片的尺寸缩放、调整图片的质量(针对JPEG、PNG等)、使用特定的算法来减少图片的数据量等,:本文主要介绍Java图片压缩三种高效... 目录一、基于OpenCV的智能尺寸压缩技术亮点:适用场景:二、JPEG质量参数压缩关键技术:压缩效果对比

Java调用C++动态库超详细步骤讲解(附源码)

《Java调用C++动态库超详细步骤讲解(附源码)》C语言因其高效和接近硬件的特性,时常会被用在性能要求较高或者需要直接操作硬件的场合,:本文主要介绍Java调用C++动态库的相关资料,文中通过代... 目录一、直接调用C++库第一步:动态库生成(vs2017+qt5.12.10)第二步:Java调用C++

Redis分片集群的实现

《Redis分片集群的实现》Redis分片集群是一种将Redis数据库分散到多个节点上的方式,以提供更高的性能和可伸缩性,本文主要介绍了Redis分片集群的实现,具有一定的参考价值,感兴趣的可以了解一... 目录1. Redis Cluster的核心概念哈希槽(Hash Slots)主从复制与故障转移2.