一、配置类以及配置文件
配置类主要作用是声明消息队列的名称
@Configuration public class TestMqConfig {
public static final String TEST_DIRECT_QUEUE = "test-queue";
/** * 创建直连式队列 * * @return org.springframework.amqp.core.Queue */ @Bean public Queue yadoQueue() { return new Queue(TEST_DIRECT_QUEUE, true); }
}
|
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource username: root password: root url: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&allowPublicKeyRetrieval=true druid: #初始化大小,最小,最大,超时链接,空闲时间,生产时间,pscache initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 rabbitmq: host: 127.0.0.1 port: 5672 username: guest password: guest
|
二、开发消息生产者
@Service public class TestProducer {
@Resource private RabbitTemplate rabbitTemplate;
public void sendMessage(String message) { rabbitTemplate.convertAndSend(TestMqConfig.TEST_DIRECT_QUEUE, message); }
}
|
三、开发消息消费者
@Component @Slf4j public class TestConsumer {
@RabbitListener(queues = TestMqConfig.TEST_DIRECT_QUEUE) @RabbitHandler public void getMessage(Object object) { log.info("消息:消费者={}", object); }
}
|
四、使用定时任务调度生产者进行测试
@Component @Slf4j public class TestScheduled {
@Resource TestProducer testProducer;
@Scheduled(cron = "0/10 * * * * ? ") public void testSend() { String msg = System.currentTimeMillis() + "msg"; testProducer.sendMessage(msg); }
}
|
启动应用程序即可在控制台看到消费者消费消息