本文主要是介绍mq_生产者,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
添加依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-activemq</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.38</version>
</dependency>
application.properties
spring.activemq.broker-url=tcp://127.0.0.1:61616
spring.activemq.user=admin
spring.activemq.password=admin
queue=mytest
server.port=8081
注入配置文件
import javax.jms.Queue;import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class QueueConfig {@Value("${queue}")private String queueName;@Beanpublic Queue queue() {return new ActiveMQQueue(queueName);}}
调用如下:
import java.util.UUID;import javax.jms.Queue;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;import com.alibaba.fastjson.JSONObject;
import com.kejin.entity.UserEntity;@Component
@EnableScheduling
public class Producer {@Autowiredprivate JmsMessagingTemplate jmsMessagingTemplate;@Autowiredprivate Queue queue;private int age = 18;@Scheduled(fixedDelay = 5000)public void send() {age++;UserEntity userEntity = new UserEntity(System.currentTimeMillis(), UUID.randomUUID().toString(), age);String json = new JSONObject().toJSONString(userEntity);System.out.println("json:" + json);jmsMessagingTemplate.convertAndSend(queue, json);}}
这篇关于mq_生产者的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!