用springboot做一个雨雪天气给自己发邮件的项目

3,442 阅读2分钟

项目目标

每天早上7点跑定时任务,调用天气预报api,如果当天是雨雪天气,就发邮件提醒

需要资源

一台阿里云轻量服务器 注册聚合数据账号,也可以用和风天气api www.juhe.cn/ 发邮件的邮箱账号,我用的是网易邮箱。 进入设置,开启IAMP和POP3服务,复制授权码,待会儿有用 image.png

代码实现

调用api查询天气

public Weather queryWeather(String cityName) {
    Map<String, Object> params = new HashMap<>();//组合参数
    params.put("city", cityName);
    params.put("key", weatherConfig.getApiKey());
    String queryParams = urlencode(params);

    String responseJsonStr = doGet(weatherConfig.getApiUrl(), queryParams);
    try {
        JSONObject response = new JSONObject(responseJsonStr);
        int error_code = response.getInt("error_code");
        if (error_code == 0) {
            System.out.println("调用接口成功");

            JSONObject result = response.getJSONObject("result");
            JSONArray future = result.getJSONArray("future");
            String todayDate = DateUtil.formatDate(new Date());
            for (int i = 0; i < future.size(); i++) {
                JSONObject jsonObj = future.getJSONObject(i);
                String date = jsonObj.getStr("date");
                if (!todayDate.equals(date)) {
                    continue;
                }
                String weatherStr = jsonObj.getStr("weather");
                String temperature = jsonObj.getStr("temperature");
                String[] temperatureArr = temperature.split("/");
                Integer minTemperature = ReUtil.getFirstNumber(temperatureArr[0]);
                Integer maxTemperature = ReUtil.getFirstNumber(temperatureArr[1]);

                Weather weather = new Weather();
                weather.setDate(date);
                weather.setWeather(weatherStr);
                weather.setMinTemperature(minTemperature);
                weather.setMaxTemperature(maxTemperature);
                return weather;
            }
            return null;
        } else {
            System.out.println("调用接口失败:" + response.getStr("reason"));
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

发送邮件

public void send(Weather weather) {
    String text = String.format("今天是%s, 天气%s, 最高温度%d, 最低温度%d",
            weather.getDate(),
            weather.getWeather(),
            weather.getMaxTemperature(),
            weather.getMinTemperature());
    mailService.sendSimpleMail(mailUserConfig.getList(), text);
}
public void sendSimpleMail(List<MailUser> userList, String text) {
    for (MailUser user : userList) {
        try {
            // 创建简单邮件消息
            SimpleMailMessage message = new SimpleMailMessage();
            // 谁发的
            message.setFrom("mundane799699@163.com");
            // 谁要接收
            message.setTo(user.getMailAddress());
            // 邮件标题
            message.setSubject("天气预报");
            String newText = String.format("亲爱的%s,\n%s", user.getName(), text);
            // 邮件内容
            message.setText(newText);
            mailSender.send(message);
        } catch (MailException e) {
            e.printStackTrace();
        }
    }
}

创建一个定时任务

@Component
public class WeatherTask {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private WeatherService weatherService;

    @Scheduled(cron = "0 0 7 * * ?")
    public void cron() {
        try {
            Weather weather = weatherService.queryWeather("杭州");
            String weatherStr = weather.getWeather();
            if (weatherStr.contains("雨") || weatherStr.contains("雪") || weatherStr.contains("雷")) {
                scheduleService.send(weather);
                System.out.println("发送成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发送失败");
        }
    }
}

部署到服务器

先安装alibaba toolkit插件 远程连接到阿里云,先给服务器安装jdk,可参考后面的参考文章。
创建/springboot目录和/scripts目录。
/springboot是个空目录,/scripts中放一个服务启动的脚本。
脚本内容如下:

nohup java -jar /springboot/mail-0.0.1-SNAPSHOT.jar > nohup.log 2>&1 &

用mvn package -Dmaven.test.skip=true 生成一下jar包 使用cloud toolkit部署,参考Cloud Toolkit 部署应用到阿里云轻量应用服务器 image.png 远程连接服务器,用ps -ef命令看一下进程是否起来

测试效果

调用接口看看效果

@RestController
@RequestMapping("/weather")
public class WeatherController {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private WeatherService weatherService;

    @GetMapping("/send")
    public String sendWeatherReport() {
        try {
            Weather weather = weatherService.queryWeather("杭州");
            scheduleService.send(weather);
        } catch (Exception e) {
            e.printStackTrace();
            return "发送失败";
        }
        return "发送成功";
    }
}

最后再附上一个配置文件的代码吧

server:
  port: 8088
spring:
  mail:
    host: smtp.163.com
    port: 465
    username: 你的邮箱
    password: 你的邮箱授权码
    protocol: smtps
mail:
  weather:
    apiUrl: http://apis.juhe.cn/simpleWeather/query
    apiKey: 你的apikey
  user:
    list:
      -
        name: 圆圆
        mailAddress: 发件人邮箱
      -
        name: 壮壮
        mailAddress: 发件人邮箱
      -
        name: 旺仔
        mailAddress: 发件人邮箱

参考

部署SpringBoot到阿里云
Cloud Toolkit 部署应用到阿里云轻量应用服务器
快速优雅的在linux服务器上安装jdk8
阿里云轻量应用服务器端口开放防火墙设置教程
阿里云轻量应用服务器和ECS云服务器差别有什么不同?
Linux中Kill进程的N种方法
maven跳过单元测试-maven.test.skip和skipTests的区别