sprigboot异步任务入门、springboot发qq有邮件、springboot发信息

2024-02-11 18:59

本文主要是介绍sprigboot异步任务入门、springboot发qq有邮件、springboot发信息,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

  • sprigboot异步任务问题引入
  • 异步注解
  • 异步简单应用代码
    • AsyncService代码
    • AsyncController代码
    • AsynchronousApplication启动类代码
  • springboot异步任务的应用场景
  • springboot发qq邮件
    • 导入依赖
    • application.yml配置
    • 测试代码
      • 简单点的邮件发送
      • 复杂点的邮件发送
    • 效果
      • 简单邮件发送截图
      • 复杂(相对上一个)邮件发送截图
    • springboot邮件发送附件截图
  • 发信息
    • springboot问题引入
    • 阿里云短信教程
      • 导入依赖
      • 教程
        • 信息模板审核
        • 签名名称审核
    • 代码
        • 结果
    • 其他短信发送
      • 网址
      • 三网短信
        • 测试
        • 代码
          • 依赖
  • springboot定时任务
    • corn表达式
    • 定时任务代码
      • AsynchronousApplication启动类代码
      • ScheduleService代码
  • 例子


sprigboot异步任务问题引入

线程的睡眠,导致加载不到下面的返回值,所以要用到异步任务

异步注解

  • @EnableAsync
  • @Async

@EnableAsync 加在springboot启动类中
@Async 加在方法中


异步简单应用代码

AsyncService代码

@Service
@Component	//@Service导包的地址可能导错,所以用@Component和@Service是一样的
public class AsyncService {//异步方法,需要添加异步注解@Asyncpublic void asynchronous() {try {Thread.sleep(5000);}catch (Exception e) {e.printStackTrace();}System.out.println("正在加载数据");}
}

AsyncController代码

@RestController
public class AsyncController {@Autowiredprivate AsyncService asyncService;@RequestMapping("/async")public String asynchronous(){asyncService.asynchronous();return "hello asynchronous";}
}

AsynchronousApplication启动类代码

@EnableAsync		//开启异步任务
@SpringBootApplication
public class AsynchronousApplication {public static void main(String[] args) {SpringApplication.run(AsynchronousApplication.class, args);}}

springboot异步任务的应用场景

  • 发邮件
  • 发信息
  • app消息推送
  • 定时任务

springboot发qq邮件

导入依赖

<!--        mail--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>

application.yml配置

在qq邮箱账户开启邮件服务

开启邮件服务截图

spring:mail:username: 18225xxxxx@qq.ocm#授权码password: snuhtmpxqxyjdidf#视情况而定,网易smtp.163.com 新浪...host: smtp.qq.comproperties:mail:stmp:ssl:enable: true

测试代码

简单点的邮件发送

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;@SpringBootTest
class AsynchronousApplicationTests {@AutowiredJavaMailSenderImpl javaMailSender;@Testvoid contextLoads() {SimpleMailMessage mailMessage = new SimpleMailMessage();mailMessage.setSubject("klz");mailMessage.setText("测试sprinboot邮件发送");mailMessage.setTo("1822xxxxx@qq.com");mailMessage.setFrom("18225xxxxx@qq.com");javaMailSender.send(mailMessage);}}

复杂点的邮件发送

 @Testvoid contextLoads2() {//复杂邮件MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();try {MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true, "utf-8");//主题mimeMessageHelper.setSubject("klz");StringBuffer stringBuffer = new StringBuffer();stringBuffer.append("<h3 style='color:hotpink'>测试sprinboot邮件发送</h3>").append("<p style='color:green'>hello this only a example!</p>");//文本mimeMessageHelper.setText(stringBuffer.toString(),true);//获取文件路径的两种方式//第一种//Resource resource = new ClassPathResource("static/haha.gif");//File sourceFile =  resource.getFile();// 有些系统提示找不到资源,可以把上面的代码换成下面这句:ClassPathResource resource = new ClassPathResource("static/haha.gif");System.out.println(resource.getURL());File sourceFile =  resource.getFile();System.out.println(sourceFile.getAbsolutePath());//第二种//File file = ResourceUtils.getFile("classpath:static/haha.gif");//System.out.println(file.getAbsolutePath());//附件
//            mimeMessageHelper.addAttachment("aa.png", new File(file.getAbsolutePath()));mimeMessageHelper.addAttachment("aa.png", sourceFile);mimeMessageHelper.setTo("18225xxxxx@qq.com");mimeMessageHelper.setFrom("18225xxxxx@qq.com");//发送javaMailSender.send(mimeMailMessage);}catch (Exception e) {e.printStackTrace();}}

效果

简单邮件发送截图

springboot邮件发送截图

复杂(相对上一个)邮件发送截图

springboot邮件发送附件截图

发信息

springboot问题引入

  • 怎么发短信?
  • 发短信必须用第三方接口吗?

回答: https://zhidao.baidu.com/question/1452646173341952780.html

阿里云短信教程

导入依赖

Java SDK文档:https://help.aliyun.com/document_detail/66496.html?spm=a2c1g.8271268.10000.119.772fdf25aDJoI0

找一个第三方发短信的接口,这里用的是阿里的
<!--       message--><dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-core</artifactId><version>4.4.6</version></dependency><dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-ecs</artifactId><version>4.17.6</version></dependency><dependency><groupId>org.json</groupId><artifactId>json</artifactId><version>20190722</version></dependency>

教程

Java SDK文档:https://help.aliyun.com/document_detail/66496.html?spm=a2c1g.8271268.10000.119.772fdf25aDJoI0

签名和消息模板审核完成才可以使用

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

信息模板审核
信息模板一般容易通过审核

在这里插入图片描述

签名名称审核
签名名称,最好讲出你做的东西的名称,我搞了很多次,都审核失败了。申请说明写的有礼貌点,这个是人审核的。

在这里插入图片描述

代码

更换自己的AccessKey ID 和 Access Key Secret 和手机号
package com.example.asynchronous.controller;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.example.asynchronous.config.RestTemplateConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Random;@RestController
public class SendMessageController {@Autowiredprivate RestTemplateConfig restTemplateConfig;//可以进行一下封装,因为实际情况是传入手机号当作参数@RequestMapping("/sendMessage")public String sendMessagefOne() {//将阿里云的代码考过来,当然也可以将代码放到service中,通过controller调用//更换自己的AccessKey ID 和 	Access Key Secret 和 电话号DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", AccessKey ID, Access Key Secret);IAcsClient client = new DefaultAcsClient(profile);CommonRequest request = new CommonRequest();request.setSysMethod(MethodType.POST);request.setSysDomain("dysmsapi.aliyuncs.com"); //第三方网址request.setSysVersion("2017-05-25");        //版本request.setSysAction("SendSms");            //定值request.putQueryParameter("RegionId", "cn-hangzhou");request.putQueryParameter("PhoneNumbers", "1837100xxxx");   //手机号request.putQueryParameter("SignName", "个人短信验证码");    //签名//验证码request.putQueryParameter("TemplateCode", "SMS_184105552"); //模板codeString code = randomUtils();        //获取6位的0-9随机数request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");//可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
//        request.putQueryParameter("SmsUpExtendCode", "90999");//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者request.putQueryParameter("OutId", "klz");try {CommonResponse response = client.getCommonResponse(request);System.out.println(response.getData());} catch (ServerException e) {e.printStackTrace();} catch (ClientException e) {e.printStackTrace();}return "信息发送成功!";}//随机数public String randomUtils() {String code = "";Random r = new Random();for(int i = 0; i <= 5; i++) {code += r.nextInt(9);}return code;}}
结果
{"Message": "账户余额不足","RequestId": "B838DED4-6061-4680-9AA0-64B122782496","Code": "isv.AMOUNT_NOT_ENOUGH"
}

在这里插入图片描述
在这里插入图片描述

没钱,没法继续了,但是大体应该是这样子的!

其他短信发送

网址

https://www.aliyun.com/citiao/3223886.html

在这里插入图片描述

三网短信

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

测试
在这里加签名,不然会出错,【xxx】内容,我在这跳了个坑

在这里插入图片描述
在这里插入图片描述

代码
依赖
 <dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.2.1</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.2.1</version></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency>
把下面这代码放到一个controller类下就行了
//随机数public String randomUtils() {String code = "";Random r = new Random();for(int i = 0; i <= 5; i++) {code += r.nextInt(9);}return code;}@RequestMapping("/sendMessage2")public String sendMessage() {String host = "http://zhiqimsms.market.alicloudapi.com";String code = randomUtils();        //获取6位的0-9随机数String path = "/sms/send/1837100xxx/【短信测试的验证码】:"+code;String method = "POST";String appcode = "086b38f3adc141e1b4b1f38be584eac6";Map<String, String> headers = new HashMap<String, String>();//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105headers.put("Authorization", "APPCODE " + appcode);Map<String, String> querys = new HashMap<String, String>();Map<String, String> bodys = new HashMap<String, String>();try {/*** 重要提示如下:* HttpUtils请从* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java* 下载** 相应的依赖请参照* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml*/HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);System.out.println(response.toString());//获取response的body//System.out.println(EntityUtils.toString(response.getEntity()));} catch (Exception e) {e.printStackTrace();}return "发送信息成功";}

在这里插入图片描述

大家只有5次的机会,谨慎使用!

springboot定时任务

corn表达式

corn百度百科:https://baike.baidu.com/item/cron/10952601?fr=aladdin
corn表达式参考文档:https://www.cnblogs.com/dubhlinn/p/10740838.html

这里只写了一部分
  • M: 分钟(0-59)。
  • H:小时(0-23)。
  • D:天(1-31)。
  • m: 月(1-12)。
  • d: 一星期内的天(0~7,0和7均为星期天)。
意义表达式
每隔10秒钟执行一次*/10 * * * * ?
每隔5分钟执行一次0 */5 * * * ?
每天1点执行一次0 0 1 * * ?
每天24点执行一次0 0 24 * * ?
每月最后一天24点执行一次0 0 24 L * ?
每月最后一个周五,每隔2小时执行一次0 0 */2 ? * 6L
每月的第三个星期五上午10:15执行一次0 15 10 ? * 5#3
在每天下午2点到下午2:05期间的每1分钟执行0 0-5 14 * * ?
每月的第三个星期五上午10:20执行一次0 20 10 ? * 6#3
每分钟的第10秒与第20秒都会执行10,20 * * * * ?

定时任务代码

AsynchronousApplication启动类代码

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;@EnableAsync            //开启异步任务
@EnableScheduling       //开启定时任务
@SpringBootApplication
public class AsynchronousApplication {public static void main(String[] args) {SpringApplication.run(AsynchronousApplication.class, args);}
}

ScheduleService代码

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;@Service
public class ScheduleService {//指定时间执行指定任务//corn表达式//"秒域 分域 时域 日域 月域 周域 年域"@Scheduled(cron = "40 0 9 * * 0-7")public void taskSchedule() {System.out.println("执行定时任务!");}
}

例子

链接:https://pan.baidu.com/s/18EkyaIe7acdpqvWVB8wgyw
提取码:fysx

这篇关于sprigboot异步任务入门、springboot发qq有邮件、springboot发信息的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/700586

相关文章

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.

Spring AI集成DeepSeek的详细步骤

《SpringAI集成DeepSeek的详细步骤》DeepSeek作为一款卓越的国产AI模型,越来越多的公司考虑在自己的应用中集成,对于Java应用来说,我们可以借助SpringAI集成DeepSe... 目录DeepSeek 介绍Spring AI 是什么?1、环境准备2、构建项目2.1、pom依赖2.2