SpringBoot -- asynchronous task, scheduled task, mail task

  • Asynchronous task

In Java applications, most of the interaction processing is realized through synchronization; however, when dealing with the interaction with the third-party system, it is easy to cause slow response. Most of the previous tasks are completed by using multi-threaded. In fact, after Spring 3.x, @ Async has been built-in to solve this problem perfectly.

Two notes:

@EnableAysnc: enable asynchronous processing

@EnableAsync
@SpringBootApplication
public class SpringbootIntegrateTaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootIntegrateTaskApplication.class, args);
    }

}

@Aysnc: marked as asynchronous

@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

    @RequestMapping("/hello")
    public String sayHello(){
        asyncService.sayHello();
        return LocalDateTime.now()+"hello AsyncService. . . . . . ";
    }
}
  • Timing task

In project development, it is often necessary to perform some scheduled tasks, such as analyzing the log information of the previous day in the early morning every day. Spring provides a way for us to perform task scheduling asynchronously, and provides TaskExecutor and TaskScheduler interfaces.

Two notes:

@Enable scheduling: enable scheduled tasks

@EnableScheduling
@SpringBootApplication
public class SpringbootIntegrateTaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootIntegrateTaskApplication.class, args);
    }

}

@Scheduled: scheduled task execution

@Service
public class ScheduledService {
    /**
     * second(Second, minute, hour, day of month, month, day of week
     * 0 * * * * MON-FRI
     *  [0 0/5 14,18 * * ?] Every day at 14:00 and 18:00, every 5 minutes
     *  [0 15 10 ? * 1-6] Once a month from Monday to Saturday at 10:15
     *  [0 0 2 ? * 6L]At 2 a.m. on the last Saturday of each month
     *  [0 0 2 LW * ?]Once at 2 a.m. on the last working day of each month
     *  [0 0 2-4 ? * 1#1]From 2:00 a.m. to 4:00 a.m. on the first Monday of each month, it will be executed once every whole hour;
     */
    // @Scheduled(cron = "0 * * * * MON-SAT")
    //@Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")
    // @Scheduled(cron = "0-4 * * * * MON-SAT")
    @Scheduled(cron = "0/4 * * * * 0-7")  //Every 4 seconds
    public void hello(){
        System.out.println("hello ... ");
    }
}

1. cron expression

field

Allowable value

Special characters allowed

 

Special characters

Representative meaning

second

0-59

, - * /

 

,

enumeration

branch

0-59

, - * /

 

-

Section

hour

0-23

, - * /

 

*

Arbitrarily

date

1-31

, - * ? / L W C

 

/

step

Month

1-12

, - * /

 

?

Day / week conflict match

week

0-7 or SUN-SAT 0,7 is SUN

, - * ? / L C #

 

L

Last

       

W

Working day

       

C

Calculated value after contacting calendar

       

#

Week, 4 × 2, the second Thursday

 

 

 

 

 

 

 

 

 

 

  • Mail task

1. Bring in the starter to send mail

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

2. Autoconfig class MailSenderAutoConfiguration

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ MimeMessage.class, MimeType.class, MailSender.class })
@ConditionalOnMissingBean(MailSender.class)
@Conditional(MailSenderCondition.class)
@EnableConfigurationProperties(MailProperties.class)
@Import({ MailSenderJndiConfiguration.class, MailSenderPropertiesConfiguration.class })
public class MailSenderAutoConfiguration {

3. JavaMailSenderImpl, a mail sending component

@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(prefix = "spring.mail", name = "host")
class MailSenderPropertiesConfiguration {

	@Bean
	@ConditionalOnMissingBean(JavaMailSender.class)
	JavaMailSenderImpl mailSender(MailProperties properties) {
		JavaMailSenderImpl sender = new JavaMailSenderImpl();
		applyProperties(properties, sender);
		return sender;
	}

4. MailProperties for mail sending

@ConfigurationProperties(prefix = "spring.mail")
public class MailProperties {

	private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

	/**
	 * SMTP server host. For instance, `smtp.example.com`.
	 */
	private String host;

	/**
	 * SMTP server port.
	 */
	private Integer port;

	/**
	 * Login user of the SMTP server.
	 */
	private String username;

	/**
	 * Login password of the SMTP server.
	 */
	private String password;

	/**
	 * Protocol used by the SMTP server.
	 */
	private String protocol = "smtp";

	/**
	 * Default MimeMessage encoding.
	 */
	private Charset defaultEncoding = DEFAULT_CHARSET;

	/**
	 * Additional JavaMail Session properties.
	 */
	private Map<String, String> properties = new HashMap<>();

	/**
	 * Session JNDI name. When set, takes precedence over other Session settings.
	 */
	private String jndiName;
#Configure email address
spring.mail.username=wmy940816@qq.com
#Configure mailbox name
spring.mail.password=avnhkarrnadsbfgd
#Configure the host of the mailbox
spring.mail.host=smtp.qq.com

5) , test mail sending

@SpringBootTest
class SpringbootIntegrateTaskApplicationTests {

    @Autowired
    JavaMailSender mailSender;

    /**
     * Test sending mail
     */
    @Test
    void contextLoads() {
        SimpleMailMessage message = new SimpleMailMessage();
        //theme
        message.setSubject("Holiday notice");
        //content
        message.setText("4 Three days off on April 4, May 6");

        //To whom?
        message.setTo("wangmingyong2017@126.com");
        //From whom?
        message.setFrom("wmy940816@qq.com");

        mailSender.send(message);
    }


    /**
     * Test sending complex mail
     */
    @Test
    public void testSendEmail() throws Exception{
        //Create a complex message message
        MimeMessage mailMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mailMessage,true);


        //theme
        helper.setSubject("Holiday notice");
        //content
        helper.setText("<h1 style='color:red'>4 Three days off on April 4, May 6</h1>",true);

        //To whom?
        helper.setTo("wangmingyong2017@126.com");
        //From whom?
        helper.setFrom("wmy940816@qq.com");

        //Upload attachments
        helper.addAttachment("1.jpg",new File("C:\\Users\\a\\Desktop\\1.jpg"));

        mailSender.send(mailMessage);
    }

}

104 original articles published, 10 praised, 110000 visitors+
Private letter follow

Tags: Spring Session Java encoding

Posted on Sun, 15 Mar 2020 06:07:04 -0400 by jervo