多个用户如何使用spring boot使用rabbitmq发送消息

时间:2015-07-30 12:43:26

标签: java spring spring-boot spring-amqp spring-messaging

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

@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);

我应该把它作为抽象类,我的每个操作/过程都应该扩展它吗?什么是最好的方法?  我可以更好地完成上述过程吗?

1 个答案:

答案 0 :(得分:1)

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

使用

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

不需要每个子类。