<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>javax.mailgroupId>
<artifactId>mailartifactId>
<version>1.4.7version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.8version>
dependency>
package com.wpj;
import org.junit.Test;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendEmail {
public static void main(String[] args) throws Exception {
SendEmailInfoUser("[email protected]", "测试标题", "测试内容", "[email protected]");
}
private static Message createSimpleMail(Session session, String sendAddress, String title, String content, String copysendAddress) throws Exception {
// 创建邮件对象
MimeMessage message = new MimeMessage(session);
// 指明邮件的发件人
message.setFrom(new InternetAddress("[email protected]"));
// 指明邮件的收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(sendAddress));
// 邮件的标题
message.setSubject(title);
// 邮件的内容
message.setContent(content, "text/html;charset=UTF-8");
// 设置抄送人
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(copysendAddress));
return message;
}
public static void SendEmailInfoUser(String sendAddress, String title, String content, String copySendAddress) throws Exception {
Properties properties = new Properties();
// 设置服务器名称
properties.setProperty("mail.host", "smtp.qq.com");
// 设置邮件传输协议
properties.setProperty("mail.transport.protocol", "smtp");
//设置是否要验证服务器用户名和密码
properties.setProperty("mail.smtp.auth", "true");
// 1.创建客户端与邮箱服务器的Session对象
Session session = Session.getInstance(properties);
// 2.开启session的debug模式,方便查看发送email的运行状态
session.setDebug(true);
// 3.通过session得到transport传输对象
Transport transport = session.getTransport();
// 4.使用用户名密码连接上邮箱服务器,此处的密码需要到邮箱开启服务设置
transport.connect("smtp.qq.com", "[email protected]", "授权码");
// 5.创建邮件
Message message = createSimpleMail(session, sendAddress, title, content, copySendAddress);
// 6.发送邮件
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
}
server:
port: 8084
spring:
thymeleaf:
cache: false
prefix: classpath:/templates/
package com.wpj.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMVCConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("toRegister").setViewName("register");
registry.addViewController("toLogin").setViewName("login");
registry.addViewController("toInputUsername").setViewName("inputUsername");
registry.addViewController("toUpdatePassword").setViewName("updatePassword");
}
}
package com.wpj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = "com.wpj")
public class ShopSsoApplication {
public static void main(String[] args) {
SpringApplication.run(ShopSsoApplication.class, args);
}
}
<a href="http://localhost:8084/toRegister">
<button class="btn1-l">注册button>
a>
package com.wpj.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Email implements Serializable {
private String title;
private String content;
private String to;
}
package com.wpj.service;
import com.wpj.entity.Email;
public interface IEmailService {
void sendEmail(Email email);
}
<dependency>
<groupId>com.wpjgroupId>
<artifactId>shop-service-apiartifactId>
<version>1.0-SNAPSHOTversion>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-mailartifactId>
dependency>
<dependency>
<groupId>com.alibaba.bootgroupId>
<artifactId>dubbo-spring-boot-starterartifactId>
<version>0.2.0version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-amqpartifactId>
dependency>
spring:
mail:
username: [email protected]
password: 授权码
host: smtp.qq.com
package com.wpj.service.impl;
import com.wpj.entity.Email;
import com.wpj.service.IEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
@Service
public class EmailServiceImpl implements IEmailService {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String from;
@Override
public void sendEmail(Email email) {
System.out.println("邮件发送。。。。");
// 创建一个MimeMessage
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
// 发送邮件的一个工具类
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
try {
// 设置邮件的内容
mimeMessageHelper.setSubject(email.getTitle());
mimeMessageHelper.setText(email.getContent(),true);
mimeMessageHelper.setFrom(from);
mimeMessageHelper.setTo(email.getTo());
// 发送邮件
javaMailSender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
package com.wpj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(scanBasePackages = "com.wpj", exclude = DataSourceAutoConfiguration.class)
public class EmailServiceApplication {
public static void main(String[] args) {
SpringApplication.run(EmailServiceApplication.class, args);
}
}
package com.wpj;
import com.wpj.entity.Email;
import com.wpj.service.IEmailService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
class EmailServiceApplicationTests {
@Autowired
private IEmailService emailService;
@Test
public void contextLoads() {
Email email = new Email();
email.setTitle("标题");
email.setContent("点击");
email.setTo("[email protected]");
emailService.sendEmail(email);
}
}
import com.alibaba.dubbo.config.annotation.Service;
@Service
public class EmailServiceImpl implements IEmailService {
...
}
spring:
mail:
username: [email protected]
password: bruvlwonkbtshecb
host: smtp.qq.com
rabbitmq:
host: 192.168.59.100
virtual-host: /
dubbo:
application:
name: email-service
registry:
address: zookeeper://192.168.59.100:2181
check: false
protocol:
port: -1
package com.wpj;
import com.alibaba.dubbo.config.spring.context.annotation.DubboComponentScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@DubboComponentScan(basePackages = "com.wpj.service")
public class EmailServiceApplication {
public static void main(String[] args) {
SpringApplication.run(EmailServiceApplication.class, args);
}
}
package com.wpj.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
@Bean
public FanoutExchange emailExchange(){
return new FanoutExchange("email-exchange");
}
@Bean
public Queue emailQueue(){
return new Queue("email-queue");
}
@Bean
public Binding emailQueueToEmailExchange(){
return BindingBuilder.bind(emailQueue()).to(emailExchange());
}
}
package com.wpj.listener;
import com.wpj.entity.Email;
import com.wpj.service.IEmailService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Configuration
public class EmailQueueListener {
private ExecutorService service = Executors.newFixedThreadPool(10);
@Autowired
private IEmailService emailService;
@RabbitListener(queues= "email-queue")
public void sendEmail(Email email){
service.submit(new Runnable() {
@Override
public void run() {
System.out.println("监听器中获取到邮件");
emailService.sendEmail(email);
}
});
}
}
<dependency>
<groupId>com.wpjgroupId>
<artifactId>shop-service-apiartifactId>
<version>1.0-SNAPSHOTversion>
dependency>
<dependency>
<groupId>com.alibaba.bootgroupId>
<artifactId>dubbo-spring-boot-starterartifactId>
<version>0.2.0version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-amqpartifactId>
<version>2.1.8.RELEASEversion>
dependency>
package com.wpj.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
@Bean
public FanoutExchange emailExchange(){
return new FanoutExchange("email-exchange");
}
@Bean
public Queue emailQueue(){
return new Queue("email-queue");
}
@Bean
public Binding emailQueueToEmailExchange(){
return BindingBuilder.bind(emailQueue()).to(emailExchange());
}
}
package com.wpj.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.wpj.entity.Email;
import com.wpj.service.IEmailService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/sso")
public class SSOController {
@Reference
private IEmailService emailService;
@Autowired
private RabbitTemplate rabbitTemplate;
@RequestMapping("/sendEmail")
@ResponseBody
public String sendEmail(String emailStr){
Email email = new Email();
email.setTo(emailStr);
email.setTitle("宅客微购注册验证码");
email.setContent("验证码: + xxx");
emailService.sendEmail(email);
// 给交换机发送信息
rabbitTemplate.convertAndSend("email-exchange", "", email);
return "ok";
}
}
server:
port: 8084
spring:
thymeleaf:
cache: false
prefix: classpath:/templates/
rabbitmq:
host: 192.168.59.100
virtual-host: /
dubbo:
application:
name: shop-sso
registry:
address: zookeeper://192.168.59.100:2181
check: false
consumer:
retries: 3
check: false
package com.wpj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(scanBasePackages = "com.wpj", exclude = DataSourceAutoConfiguration.class)
public class ShopSsoApplication {
public static void main(String[] args) {
SpringApplication.run(ShopSsoApplication.class, args);
}
}
package com.wpj.common.utils;
import java.util.Random;
public class CodeUtils {
public static String getCode(){
String doubleStr = new Random().nextDouble()+"";
int indexOf = doubleStr.indexOf(".");
return doubleStr.substring(indexOf +1,indexOf+7);
}
}
package com.wpj.service;
import com.wpj.entity.User;
public interface IUserService extends IBaseService<User> {
int register(User user);
User selectByUsername(String username);
}
@Override
public int register(User user) {
// 1.先判断用户名是否被注册 有返回1
User dbUser = this.selectByUsername(user.getUsername());
if(dbUser != null){
return 1;
}
// 2.在判断邮箱是否被注册 有返回2
EntityWrapper wrapper = new EntityWrapper<User>();
wrapper.eq("email",user.getEmail());
Integer emailCount = userMapper.selectCount(wrapper);
if(emailCount > 0){
return 2; // 邮箱已存在
}
// 3.注册成功 成功返回3
userMapper.insert(user);
return 3;
}
@Override
public User selectByUsername(String username) {
User user = new User();
user.setUsername(username);
return userMapper.selectOne(user);
}
server:
port: 8084
spring:
thymeleaf:
cache: false
prefix: classpath:/templates/
rabbitmq:
host: 192.168.59.100
virtual-host: /
redis:
password: admin
host: 192.168.59.100
dubbo:
application:
name: shop-sso
registry:
address: zookeeper://192.168.59.100:2181
check: false
consumer:
retries: 3
check: false
@Autowired
private RedisTemplate redisTemplate;
@RequestMapping("/sendEmail")
@ResponseBody
public String sendEmail(String emailStr){
String code = CodeUtils.getCode();
Email email = new Email();
email.setTo(emailStr);
email.setTitle("注册验证码");
email.setContent("验证码:"+code);
System.out.println(code);
// key 唯一
redisTemplate.opsForValue().set(emailStr + "_code", code,60, TimeUnit.SECONDS);
emailService.sendEmail(email);
// 给交换机发送信息
rabbitTemplate.convertAndSend("email-exchange", "", email);
return "ok";
}
@RequestMapping(value = "/register")
@ResponseBody
public ResultEntity register(User user, String code){
// 1.判断code是否有效
String redisCode= (String)redisTemplate.opsForValue().get(user.getEmail()+ "_code");
System.out.println(redisCode);
if(redisCode != null && redisCode.equals(code)){
int result = userService.register(user);
if(result == 1){
return ResultEntity.FALL("用户名已被注册");
}else if(result == 2){
return ResultEntity.FALL("邮箱已被注册");
}else if(result == 3){
return ResultEntity.SUCCESS();
}
}else{
return ResultEntity.FALL("验证码错误");
}
return ResultEntity.FALL();
}
localhost:8084/toRegister
else if(result == 3){
return ResultEntity.SUCCESS("http://localhost:8084/toLogin");
}