且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Camel 的 REST 服务调用需要首先调用身份验证 api

更新时间:2023-01-18 11:26:35

遵循@gusto2 方法,它几乎工作正常.

Followed @gusto2 approach, Its pretty much working fine.

所以,我创建了两条路由 --> 第一个是基于定时器的,如下所示,它生成令牌,定期刷新它(因为路由是基于定时器的)并将令牌存储在局部变量中以供某些人重用其他路线.

SO, I created two routes --> First one is a timer based like below, this generates the token, periodically refreshes it(since the route is timer based) and stores the token in a local variable for being reused by some other route.

@Component
public class RestTokenProducerRoute extends RouteBuilder {

    private String refreshedToken;

    @Override
    public void configure() throws Exception {

        restConfiguration().producerComponent("http4");

        from("timer://test?period=1200000") //called every 20 mins
                    .process(
                            exchange -> exchange.getIn().setBody(
                                    new UserKeyRequest("apiuser", "password")))
                    .marshal(userKeyRequestJacksonFormat) //convert it to JSON
                    .setHeader(Exchange.HTTP_METHOD, constant("POST"))
                    .setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
                    .to("http4://localhost:8085/Service/Token")
                    .unmarshal(userKeyResponseJacksonFormat)
                    .process(new Processor() {
                        public void process(Exchange exchange) throws Exception {   
                            UserKeyResponse response= exchange.getIn().getBody(
                                    UserKeyResponse.class); //get the response object
                            System.out.println(response + "========>>>>>>" +  
                                    response.getResult());
                            setRefreshedToken(response.getResult()); //store the token in some object
                        }
                    }).log("${body}");
        }

        public String getRefreshedToken() {
            return refreshedToken;
        }

        public void setRefreshedToken(String refreshedToken) {
            this.refreshedToken = refreshedToken;
        }
}

第二个路由可以调用后续的api,这些api将使用第一个路由生成的令牌,它会是这样的.必须添加错误处理场景,其中令牌可能无效或过期.但我想这将是另一个需要解决的问题.

And the second route can call subsequent apis which will use the token generated by the first route, it would be something like this. Have to add error handling scenarios, where token might not be valid or expired. But I guess that would be separate concern to solve.

@Component
public class RestTokenUserOnboardRoute extends RouteBuilder  {

    private JacksonDataFormat OtherDomainUserRequestJacksonFormat = new JacksonDataFormat(
            OtherDomainUserRequest.class);
    private JacksonDataFormat OtherDomainUserResponseJacksonFormat = new JacksonDataFormat(
            OtherDomainUserResponse.class);
    @Override
    public void configure() throws Exception {

        restConfiguration().producerComponent("http4");

        //This route is subscribed to a Salesforce topic, which gets invoked when there is any new messages in the topic.
        from("salesforce:CamelTestTopic?sObjectName=MyUser__c&sObjectClass="+MyUser__c.class.getName()))
            .convertBodyTo(OtherDomainUserRequest.class)
            .marshal(OtherDomainUserRequestJacksonFormat).log("${body}")
            .setHeader(Exchange.HTTP_METHOD, constant("POST"))
            .setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
            .log("The token being passed is ==> ${bean:tokenObj?method=getRefreshedToken}")
            .setHeader("Authorization", simple("${bean:tokenObj?method=getRefreshedToken}"))
            .to("http4://localhost:8085/Service/DomainUser")
            .unmarshal(OtherDomainUserResponseJacksonFormat)
            .process(new Processor() {
            public void process(Exchange exchange) throws Exception {
                    OtherDomainUserResponse response = exchange.getIn().getBody(
                            OtherDomainUserResponse.class);
                            System.out.println(response + "==================>>>>>> " + response.getStatusCode());
                        }
            }).log("${body}");
    }
}

所以,这里的令牌是从 tokenObj bean 中消耗的(RestTokenProducerRoute 的实例,它定义了方法 getRefreshedToken().它返回存储的令牌.

So, here the token is getting consumed from the tokenObj bean (instance of RestTokenProducerRoute which has method getRefreshedToken() defined. It returns the stored token.

不用说,您已经在 camelcontext 注册表中设置了 bean 以及其他设置(如组件、路由等),如下所示.在我的情况下,如下所示.

Needless to say, you have set the bean in camelcontext registry as follows along with other settings (like component, route etc). In my case it was as follows.

@Autowired
public RestTokenUserOnboardRoute userOnboardRoute;
@Autowired
public RestTokenProducerRoute serviceTokenProducerRoute;

@Autowired
private RestTokenProducerRoute tokenObj;

@Override
protected CamelContext createCamelContext() throws Exception {
    SimpleRegistry registry = new SimpleRegistry(); 
    registry.put("tokenObj", tokenObj); //the tokenObj bean,which can be used anywhere in the camelcontext
    SpringCamelContext camelContext = new SpringCamelContext();
    camelContext.setRegistry(registry); //add the registry
    camelContext.setApplicationContext(getApplicationContext());
    camelContext.addComponent("salesforce", salesforceComponent());
    camelContext.getTypeConverterRegistry().addTypeConverter(DomainUserRequest.class, MyUser__c.class, new MyTypeConverter());
    camelContext.addRoutes(route()); //Some other route
    camelContext.addRoutes(serviceTokenProducerRoute); //Token producer Route
    camelContext.addRoutes(userOnboardRoute); //Subsequent API call route
    camelContext.start();
    return camelContext;
}

这解决了我动态设置令牌的问题,因为执行其他路由会产生令牌.

This solves my problem of setting token dynamically where token is getting produced as a result of execution of some other route.