Good afternoon, I am currently working with Apache Camel in Quarkus, basically my microservice is called identify-origin and it calls another microservice called getActivateSessionByIp, I want to apply cache to this call and I am using the following logic for the same:
Class ResRoute
@ApplicationScoped
public class RestRoute extends RouteBuilder {
@ConfigProperty(name = "client.url.userProfile")
String urlUserProfile;
@ConfigProperty(name = "client.utl.getActiveSessionByIp")
String urlGetActivateSessionByIp;
@ConfigProperty(name = "descripcion.servicio")
String descriptionService;
private ConfigureSsl configureSsl;
private static final String SALIDA_BSS_EXCEPTION = "Salida Microservicio IdentifyOrigin ${body}";
private static final String MSG_EXCEPTION = "Descripcion de la Exception: ${exception.message}";
private static final String DATE_LOG = "[${bean:BeanDate.getCurrentDateTime()}] ";
public RestRoute() {
TimeZone.setDefault(TimeZone.getTimeZone("GMT-4"));
configureSsl= new ConfigureSsl();
}
@Override
public void configure() throws Exception {
BeanDate beanDate= new BeanDate();
getContext().getRegistry().bind("BeanDate", beanDate);
restConfiguration().bindingMode(RestBindingMode.json).dataFormatProperty("json.in.disableFeatures","FAIL_ON_UNKNOWN_PROPERTIES")
.clientRequestValidation(true)
.apiProperty("api.title","IdentifyOrigin")
.apiProperty("api.description",descriptionService)
.apiProperty("api-version","1.0.0")
.apiProperty("cors","true");
rest("/")
.produces("application/json")
.consumes("application/json")
.post("/identifyOrigin/v1/info")
.type(Request.class)
.outType(ResponseSuccess.class)
.param().name("Response").type(RestParamType.body).description("Parametros de Salidas")
.endParam().to("direct:pipeline");
from("direct:pipeline")
.doTry()
.log("["+"${bean:BeanDate.getCurrentDateTime()}"+"] "+ "Valor Header x-correlator: ${header.x-correlator}")
.to("bean-validator:validateRequest")
.log("["+"${bean:BeanDate.getCurrentDateTime()}"+"] "+ "Datos de Entrada del MS: ${body}")
/*Processor classes to create the Microservice Request to call GetActiveSession and Ip */
.process(new GetActivateSessionByIpReqProcessor())
.log("n[${bean:BeanDate.getCurrentDateTime()}] "+"Entrada Microservicio GetActivateSessionByIp: ${exchangeProperty[getActivateSessionByIpRequest]}")
/* Configure the parameters for the cache*/
.setHeader(CaffeineConstants.ACTION, constant(CaffeineConstants.ACTION_GET))
.setHeader(CaffeineConstants.KEY).exchangeProperty("ipAddress")
.toF("caffeine-cache://%s", "GetActiveSessionByIpCache")
.log("Hay Resultado en Cache de la consulta asociado a la IP Consultada: ${exchangeProperty[ipAddress]} ${header.CamelCaffeineActionHasResult}")
.log("CamelCaffeineActionSucceeded: ${header.CamelCaffeineActionSucceeded}")
.choice()
/* It is queried if there is a result in the cache for the sent id*/
.when(header(CaffeineConstants.ACTION_HAS_RESULT).isEqualTo(Boolean.FALSE))
.to(configureSsl.setupSSLContext(getCamelContext(), urlGetActivateSessionByIp))
/* A process class is used to validate the response and take different actions depending on the type of response*/
.process(new GetActivateSessionByIpResProcessor())
.setHeader(CaffeineConstants.ACTION, constant(CaffeineConstants.ACTION_PUT))
.setHeader(CaffeineConstants.KEY).exchangeProperty("ipAddress")
.toF("caffeine-cache://%s", "GetActiveSessionByIpCache")
.otherwise()
.log("Cache is working")
.process(new GetActivateSessionByIpResProcessor())
.endChoice()
.end()
/* It is required to validate if the http response type is 200, 400, 404, so a log will be used to see it.*/
.log("Resultado header: ${exchangeProperty[httpResponseCode]}")
.endDoTry()
}
}
The problem happens is that at first I captured the http response value of the microservice and at first if it was 200, I got the required fields, otherwise I threw an exception and controlled response, here what I would like is how can I use the cache For these cases, it would be necessary to reformulate my code, since I am noticing that when I made my first query everything was fine, but when it goes to the cache the service does not recognize the http code variable and throws a null pointer exception
This is how my first query happens, you can see that I can see the response code in the httpResponseCode variable:
First query (not cached):
Second Query (It is cached):
I attach my processor classes so they know what it contains:
GetActivateSessionByIpReqProcessor
@ApplicationScoped
public class GetActivateSessionByIpReqProcessor implements Processor {
private final ObjectMapper objectMapper;
private final IGetActivateSessionByIpMappingReq getActivateSessionByIpMappingReq;
public GetActivateSessionByIpReqProcessor() {
objectMapper = new ObjectMapper();
getActivateSessionByIpMappingReq=new GetActivateSessionByIpMappingReqImpl();
}
@Override
public void process(Exchange exchange) throws Exception {
Request request=exchange.getIn().getBody(Request.class);
String correlatorId = Optional.ofNullable(exchange.getIn().getHeader("x-correlator")).map(Object::toString).orElse("c8ff2443-1b49-4f5f-8412-3fecbb10b836");
String ipAddress=request.getIpAddress();
String port= String.valueOf(request.getPort());
RequestGetActivateSessionByIp requestGetActivateSessionByIp=getActivateSessionByIpMappingReq.toRequest(ipAddress,port);
String jsonGetActivateSessionByIpMappingReq = objectMapper.writeValueAsString(requestGetActivateSessionByIp);
exchange.setProperty("getActivateSessionByIpRq", requestGetActivateSessionByIp);
exchange.setProperty("getActivateSessionByIpRequest", jsonGetActivateSessionByIpMappingReq);
exchange.setProperty("correlatorId", correlatorId);
exchange.setProperty("ipAddress", ipAddress);
exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "application/json");
exchange.getOut().setHeader(Exchange.HTTP_METHOD, "POST");
exchange.getOut().setHeader(Exchange.HTTP_PATH, "/api/v1/getActivateSessionByIp");
exchange.getOut().setHeader("x-transaction-id", correlatorId);
exchange.getOut().setHeader("x-user", "UsuarioKernel");
exchange.getOut().setHeader("x-token", "bc4a129867486c6ee7436fa6111c2e");
exchange.getOut().setBody(jsonGetActivateSessionByIpMappingReq);
}
}
GetActivateSessionByIpResProcessor
@ApplicationScoped
public class GetActivateSessionByIpResProcessor implements Processor {
private final ObjectMapper objectMapper;
public GetActivateSessionByIpResProcessor() {
objectMapper = new ObjectMapper();
}
@Override
public void process(Exchange exchange) throws Exception {
String bodyResponse=exchange.getIn().getBody(String.class);
String httpResponseCode=exchange.getIn().getHeader("CamelHttpResponseCode", String.class);
ResponseGetActivateSessionByIp responseGetActivateSessionByIp= objectMapper.readValue(bodyResponse,ResponseGetActivateSessionByIp.class);
String jsonGetActivateSessionByIpRs = objectMapper.writeValueAsString(responseGetActivateSessionByIp);
String phoneNumberByIp=responseGetActivateSessionByIp.getId();
exchange.setProperty("phoneNumberByIp", phoneNumberByIp);
exchange.setProperty("httpResponseCode", httpResponseCode);
}
}