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 Security常见问题及解决方案

《SpringSecurity常见问题及解决方案》SpringSecurity是Spring生态的安全框架,提供认证、授权及攻击防护,支持JWT、OAuth2集成,适用于保护Spring应用,需配置... 目录Spring Security 简介Spring Security 核心概念1. ​Securit

Python实现终端清屏的几种方式详解

《Python实现终端清屏的几种方式详解》在使用Python进行终端交互式编程时,我们经常需要清空当前终端屏幕的内容,本文为大家整理了几种常见的实现方法,有需要的小伙伴可以参考下... 目录方法一:使用 `os` 模块调用系统命令方法二:使用 `subprocess` 模块执行命令方法三:打印多个换行符模拟

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho

SpringBoot改造MCP服务器的详细说明(StreamableHTTP 类型)

《SpringBoot改造MCP服务器的详细说明(StreamableHTTP类型)》本文介绍了SpringBoot如何实现MCPStreamableHTTP服务器,并且使用CherryStudio... 目录SpringBoot改造MCP服务器(StreamableHTTP)1 项目说明2 使用说明2.1

spring中的@MapperScan注解属性解析

《spring中的@MapperScan注解属性解析》@MapperScan是Spring集成MyBatis时自动扫描Mapper接口的注解,简化配置并支持多数据源,通过属性控制扫描路径和过滤条件,利... 目录一、核心功能与作用二、注解属性解析三、底层实现原理四、使用场景与最佳实践五、注意事项与常见问题六

Spring的RedisTemplate的json反序列泛型丢失问题解决

《Spring的RedisTemplate的json反序列泛型丢失问题解决》本文主要介绍了SpringRedisTemplate中使用JSON序列化时泛型信息丢失的问题及其提出三种解决方案,可以根据性... 目录背景解决方案方案一方案二方案三总结背景在使用RedisTemplate操作redis时我们针对

Java中Arrays类和Collections类常用方法示例详解

《Java中Arrays类和Collections类常用方法示例详解》本文总结了Java中Arrays和Collections类的常用方法,涵盖数组填充、排序、搜索、复制、列表转换等操作,帮助开发者高... 目录Arrays.fill()相关用法Arrays.toString()Arrays.sort()A

Spring Boot Maven 插件如何构建可执行 JAR 的核心配置

《SpringBootMaven插件如何构建可执行JAR的核心配置》SpringBoot核心Maven插件,用于生成可执行JAR/WAR,内置服务器简化部署,支持热部署、多环境配置及依赖管理... 目录前言一、插件的核心功能与目标1.1 插件的定位1.2 插件的 Goals(目标)1.3 插件定位1.4 核

如何使用Lombok进行spring 注入

《如何使用Lombok进行spring注入》本文介绍如何用Lombok简化Spring注入,推荐优先使用setter注入,通过注解自动生成getter/setter及构造器,减少冗余代码,提升开发效... Lombok为了开发环境简化代码,好处不用多说。spring 注入方式为2种,构造器注入和setter