在序列化之前检索 RabbitMQ 消息(审计)

Retrieving a RabbitMQ message before serialization (Auditing)

我有一个对象,在将它发送到 Spring Cloud Stream 之前,我试图对其进行审核,当我将对象作为 application/json 发送时,问题就出现了,因此拦截器将对象作为序列化字符串。是否可以运行 jackson 转换器之前的拦截器?

拦截器代码如下:

@Slf4j
public class AuditInterceptor implements ChannelInterceptor {
    private void updateField(Field field, Object payload, String newValue){
        if(field.getType().equals(String.class)){
            try {
                Method readMethod =  BeanUtils.getPropertyDescriptor(payload.getClass(),field.getName()).getReadMethod();

                log.info("Old value {}", readMethod.invoke(payload));

                Method setMethod = BeanUtils.getPropertyDescriptor(payload.getClass(),field.getName()).getWriteMethod();
                setMethod.invoke(payload, newValue);

                log.info("New value {}", readMethod.invoke(payload));
            } catch (IllegalAccessException e) {
                log.error("Error", e);
            } catch (InvocationTargetException e) {
                log.error("Error", e);
            }
        }
    }

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel messageChannel) {
        for(Field field  : message.getPayload().getClass().getDeclaredFields()){

            if (field.isAnnotationPresent(CreatedBy.class)){
                updateField(field, message.getPayload(), "Interceptor");
            }

            if (field.isAnnotationPresent(LastModifiedBy.class)){
                updateField(field, message.getPayload(), "Interceptor");
            }
        }

        return message;
    }
}

运行ner 的代码:

@Component
public class AuditRunner implements CommandLineRunner {
    @Autowired
    ChannelInterceptor auditInterceptor;

    @Autowired
    MessageChannel output;

    @Override
    public void run(String... strings) throws Exception {
        ((DirectChannel) output).addInterceptor(auditInterceptor);
    }
}

尝试...

((DirectChannel) output).addInterceptor(0, auditInterceptor);

...所以首先应用你的拦截器(转换由拦截器执行)。