gpt4 book ai didi

java - 如何使用 spring boot 多个用户通过rabbitmq发送消息

转载 作者:行者123 更新时间:2023-12-01 11:16:49 24 4
gpt4 key购买 nike

我的目标:我有多个并行运行的作业(进程)(单独的线程)。我想实现消息传递,以便每个进程都可以向rabbitmq服务器发送消息(如果需要)。 现在我有了这个

@Configuration
public class SenderConfiguration {

String content = "";
String host = "";
String port = "";
String userName = "";
String password = "";
String queueName = "";
InputStream input = null;

public SenderConfiguration() {
init();
}

private void init() {
Properties prop = new Properties();
try {
input = new FileInputStream("R.CONFIGURATION_FILE_PATH");
host = prop.getProperty("messaging.host");
port = prop.getProperty("messaging.port");
userName = prop.getProperty("messaging.userName");
password = prop.getProperty("messaging.password");
queueName = prop.getProperty("messaging.queue");
} catch (FileNotFoundException e) {

e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

@Bean
public RabbitTemplate rabbitTemplate() {
RabbitTemplate template = new RabbitTemplate(connectionFactory());
template.setRoutingKey(this.queueName);
return template;
}

@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(
this.host);
connectionFactory.setUsername(userName);
connectionFactory.setPassword(password);
return connectionFactory;
}

@Bean
public ScheduledProducer scheduledProducer() {
return new ScheduledProducer();
}

@Bean
public BeanPostProcessor postProcessor() {
return new ScheduledAnnotationBeanPostProcessor();
}

static class ScheduledProducer {

@Autowired
private volatile RabbitTemplate rabbitTemplate;

private final AtomicInteger counter = new AtomicInteger();

@Scheduled(fixedRate = 1000)
public void sendMessage(String message) {
rabbitTemplate.convertAndSend("Roxy " + counter.incrementAndGet());
}
}

}

并从我的一个操作中调用它

new AnnotationConfigApplicationContext(SenderConfiguration.class);

我应该将其设为抽象类,并且我的每个操作/过程都应该扩展它吗?最好的方法是什么? 我可以让上述过程变得更好吗?

最佳答案

只需使用带有属性占位符的单个类...

使用

@Value("${messaging.host}")
String host;

等等

不需要每个子类。

关于java - 如何使用 spring boot 多个用户通过rabbitmq发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31724112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com