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)

相关推荐
飘尘18 小时前
前端转型全栈(Java后端)的快速上手指引
前端·后端·全栈
浏览器工程师19 小时前
AI Agent 接浏览器任务,先别让它一路点到底
前端·后端
行者全栈架构师19 小时前
Maven dependency:tree 的 8 个高级用法
java·后端
Chenyiax19 小时前
从一次请求看懂 OkHttp:架构、调度与连接管理
后端
爱勇宝20 小时前
深扒 Anthropic 1680 位工程师简历:应届生几乎没机会,AI 公司最缺的不是博士
前端·后端·程序员
AskHarries20 小时前
工具失败时怎么办:重试、回滚、人工确认和风险提示
后端·程序员
苏三说技术1 天前
Claude Code从失控到起飞,只用了这些技巧
后端
长栎1 天前
写 for 循环写了十年,你却从没用过迭代器模式最狠的那一面
后端
LiaCode1 天前
Redis 在生产项目的使用
前端·后端
用户559822481221 天前
Docker Compose Down 导致容器数据误删——ext4 日志恢复全记录
后端