Forest调用注册到nacos服务中心的服务

背景:forest在开发的时候已经使用了很久,但是好像目前还不支持调用注册到服务中心的服务。为了让不行变成行,特意写了这篇博客。 做法:第一步,自定义注解NacosService.

java 复制代码
import com.dtflys.forest.annotation.MethodLifeCycle;
import com.dtflys.forest.annotation.RequestAttributes;

import java.lang.annotation.*;

@Documented
/** 重点: @MethodLifeCycle注解指定该注解的生命周期类*/
@MethodLifeCycle(ServiceNameCycle.class)
// 加上 @@RequestAttributes 以标识该注解的属性可以被解析
@RequestAttributes
@Retention(RetentionPolicy.RUNTIME)
/** 指定该注解可用于类上或方法上 */
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface NacosService {
    /**
     * 自定义注解的属性:服务名
     * 所有自定注解的属性可以在生命周期类中被获取到
     */
    String serviceName();
}

定义ServiceNameCycle来解析自定义的注解

typescript 复制代码
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.lifecycles.MethodAnnotationLifeCycle;
import com.dtflys.forest.reflection.ForestMethod;

public class ServiceNameCycle implements MethodAnnotationLifeCycle<NacosService, Object> {


    /**
     * 当方法调用时调用此方法,此时还没有执行请求发送
     * 此方法可以获得请求对应的方法调用信息,以及动态传入的方法调用参数列表
     */
    @Override
    public void onInvokeMethod(ForestRequest request, ForestMethod method, Object[] args) {
        Object serviceName = getAttribute(request, "serviceName");
        request.setHost(serviceName.toString());
    }

    /**
     * 发送请求前执行此方法,同拦截器中的一样
     */
    @Override
    public boolean beforeExecute(ForestRequest request) {
        return true;
    }

    /**
     * 此方法在请求方法初始化的时候被调用
     */
    @Override
    public void onMethodInitialized(ForestMethod method, NacosService annotation) {
    }
}

第三步,需要在拦截器里面解析这个。这里插播一条小知识:通过serviceName获取对应的链接信息。

java 复制代码
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.interceptor.Interceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.URI;
import java.util.Objects;

@Slf4j
@Component
public class ForestInterceptor<T> implements Interceptor<T> {

    @Resource
    private LoadBalancerClient loadBalancerClient;
    /**
     * 该方法在请求发送之前被调用, 若返回false则不会继续发送请求
     * @Param request Forest请求对象
     */
    @Override
    public boolean beforeExecute(ForestRequest req) {
        log.info("invoke Simple beforeExecute");
        URI newUri = getUriByServiceName(req.getHost());
        if(Objects.nonNull(newUri)){
            req.setHost(newUri.getAuthority());
        }
        return true;  // 继续执行请求返回true
    }

    private URI getUriByServiceName(String serviceName){
        ServiceInstance choose = loadBalancerClient.choose(serviceName);
        if(Objects.nonNull(choose)){
            return choose.getUri();
        }
        return null;
    }
}

最后一步记得在配置文件加上一行配置

yaml 复制代码
forest:
  interceptors:
    - com.szah.flow.interceptor.ForestInterceptor

接下来展示怎么调用

less 复制代码
import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.annotation.Post;
import com.dtflys.forest.annotation.Query;

@NacosService(serviceName = "smarthub-rest")
public interface Restful {

    @Post("/event/getSatgeMatters")
    JSONObject getSatgeMatters(@Query("situationResultId") String situationResultId, @Query("eventId")String eventId);
}

通过上述几步,就可以实现forest调用注册到nacos的服务。 参考资料:🥪 拦截器 | Forest (dtflyx.com)

相关推荐
X² 编程说5 分钟前
14.面试算法-字符串常见算法题(三)
java·数据结构·后端·算法·面试
请不要叫我菜鸡1 小时前
Go语言基础学习02-命令源码文件;库源码文件;类型推断;变量重声明
linux·后端·golang·类型推断·短变量·变量重声明·库源码文件
AskHarries1 小时前
Spring Boot集成Akka Cluster快速入门Demo
java·spring boot·后端·akka
少喝冰美式1 小时前
【大模型教程】如何在Spring Boot中无缝集成LangChain4j,玩转AI大模型!
人工智能·spring boot·后端·langchain·llm·ai大模型·计算机技术
lucifer3112 小时前
深入理解 Spring Boot 自动配置原理
java·后端
岁岁岁平安2 小时前
《飞机大战游戏》实训项目(Java GUI实现)(设计模式)(简易)
后端·游戏·设计模式·飞机大战·java-gui
JavaGuide2 小时前
一条 SQL 语句在 MySQL 中是如何执行的?
java·数据库·后端·mysql
ABin-阿斌3 小时前
SpringBoot 整合 Easy_Trans 实现翻译的具体介绍
java·spring boot·后端
终末圆3 小时前
MyBatis XML映射文件编写【后端 18】
xml·java·开发语言·后端·算法·spring·mybatis
_.Switch3 小时前
Python Web 架构设计与性能优化
开发语言·前端·数据库·后端·python·架构·log4j