简体   繁体   English

Spring JMS 生产者和消费者中的相同 ThreadLocal

[英]Same ThreadLocal in Spring JMS producer and consumer

I am working on handling Cart (commercial web app) on backend side with SpringBoot and Spring JMS.我正在使用 SpringBoot 和 Spring JMS 在后端处理 Cart(商业 Web 应用程序)。 JMS producer will send Order message and consumer will pick it up and process. JMS 生产者将发送 Order 消息,消费者将接收它并进行处理。

Since application should be configured for multi-tenancy, I am keeping tenant ID in ThreadLocal.由于应用程序应配置为多租户,因此我将租户 ID 保留在 ThreadLocal 中。 On producer side, everything is fine and tenant ID is available in ThreadLocal, but it's not on consumer side.在生产者方面,一切都很好,租户 ID 在 ThreadLocal 中可用,但在消费者方面却没有。 How I can make it available on consumer side as well?我如何才能使其在消费者方面也可用?

There is no guarantee that the JMS producer and consumer will be handled by the same thread.不能保证 JMS 生产者和消费者将由同一个线程处理。 It is very unlikely to be honest.诚实的可能性很小。 Heck they can be in different JVMs which makes it impossible.哎呀,它们可以在不同的 JVM 中,这使得它不可能。 So you won't be able to pass information from the producer to the consumer using thread locals.因此,您将无法使用线程局部变量将信息从生产者传递给消费者。

You have to add this information to the body of the message or add this to as a property.您必须将此信息添加到消息正文或将其添加为属性。

Each message contains a built-in facility for supporting application-defined property values.每条消息都包含用于支持应用程序定义的属性值的内置工具。 Properties provide an efficient mechanism for supporting application-defined message filtering.属性为支持应用程序定义的消息过滤提供了一种有效的机制。

Source: Message Javadoc来源: 消息 Javadoc

Writing and reader the property is simple:写入和读取属性很简单:

// Producer side
msg.setStringProperty("tenant", "tenant-1");
// Consumer side
String tenant = msg.getStringProperty("tenant");

As soon as you extract the tenant information on the consumer side you can put it to a thread local variable for further use.在消费者端提取租户信息后,您可以将其放入线程局部变量以供进一步使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM