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)

相关推荐
万少33 分钟前
DeepSeek-V4-Flash 正式版上线了,但这 3 个坑我帮你提前踩了
前端·javascript·后端
明月_清风36 分钟前
🚀 Palantir Foundry 本体论实战:当 Ontology 从"知识图谱"进化为"企业操作系统"
前端·后端
明月_清风1 小时前
从概念到代码:用 Ontology 构建你的第一个知识图谱
前端·后端
Python私教1 小时前
Django 6.1 邮件配置大改:旧项目如何平稳升级?
后端·python·django
Python私教1 小时前
Django 6.1 升级避坑:数据库版本不兼容怎么解决?
后端·python·django
Python私教1 小时前
Django 接口开发实测:新手还需要使用 REST 框架吗?
后端·python·django
techdashen1 小时前
Go设计取舍之三: 0.3ns每次的错误Benchmark
开发语言·后端·golang
techdashen3 小时前
Go设计取舍之四: map不变时能否并发修改不同value
开发语言·后端·golang
朱容zr3331333 小时前
为什么推荐使用自增主键?使用UUID作为主键的优缺点是什么?
java·运维·数据库·后端·mysql·面试·性能优化
用户608186527903 小时前
一文吃透 Avalonia 布局容器|Grid 到 UniformGrid 核心用法 + 语法糖实战
后端