1、首先下载 activeMQ地址:https://activemq.apache.org/
下载完成以后,进行启动
启动步骤很简单,就tomcat差不多
这里要注意,看你电脑是32位还是64位,如果32位,那么就点击32位那个,我们这里以64位为例
启动完成后,一般activemq连接时是以tcp协议来连接的
接下来,我们创建一个springboot项目,创建springboot项目,这里则不写了!
创建完项目以后,我们配置文件以application.yml为例:
###这个是连接activemq的tcp连接,新下载的账号密码一般都为admin
spring:
activemq:
broker-url: tcp://127.0.0.1:61616
#账号
user: admin
#密码
password: admin
mail:
##邮件服务器
host: smtp.qq.com
##发送邮件的账号
username: ********
#QQ邮箱的授权码
password: **********
default-encoding: UTF-8
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
##这个大家都懂,项目端口号
server:
port: 8080
##创建一个属于自己的队列
my_MQ: spring-boot
##发往哪里的邮件,邮件号
email: *****@qq.com
创建生产者Producer和Consumer 消费者
@Component
public class Producer {
@Autowired
private JmsMessagingTemplate messagingTemplate;//获取jms模板
@Autowired
private Queue queue; //获取jms的队列
@Value("${email}")
private String email;
@Scheduled(fixedDelay = 5000) //每隔5秒时间向队列发送消息
public void send(){
//String msg = System.currentTimeMillis()+"";//获取时间
JSONObject obj = new JSONObject();
obj.put("username", "zzzz");
obj.put("email", email);
String msg = obj.toString();
messagingTemplate.convertAndSend(queue,msg);
}
}
@Component
public class Consumer {
@Autowired
private MailSend mailSend;
@JmsListener(destination="${my_MQ}")
public void receive(String msg){
if(StringUtils.isEmpty(msg)){
return ;
}
//解析json
JSONObject object = JSONObject.fromObject(msg);
String username = object.getString("username");
String email = object.getString("email");
mailSend.sendSimpleMail(email, username);
System.out.println("发送成功!"+object.toString());
}
}
初始化队列
@Component //注入spring容器
public class ConfigQueue {
//队列名称
@Value("${my_MQ}")
private String my_MQ;
//把队列注入到spring容器中
@Bean
private Queue queue(){
return new ActiveMQQueue(my_MQ);
}
}
发送Main邮件
@Component
public class MailSend {
@Autowired
private JavaMailSender javaMailSender;
//@Autowired
private Logger logger = LoggerFactory.getLogger(this.getClass());
public void sendSimpleMail(String email,String username) {
try {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//邮件发送人
simpleMailMessage.setFrom(email);
//邮件接收人
simpleMailMessage.setTo(email);
//邮件主题
simpleMailMessage.setSubject("注册通知!");
//邮件内容
simpleMailMessage.setText("恭喜"+username+"注册成功,请回到登陆页面进行登陆!");
javaMailSender.send(simpleMailMessage);
} catch (Exception e) {
logger.error("邮件发送失败", e.getMessage());
}
}
}
springboot启动类
@SpringBootApplication
@EnableScheduling
public class CsdndemoApplication {
public static void main(String[] args) {
SpringApplication.run(CsdndemoApplication.class, args);
}
}