Java course experiment Spring Boot task management

1. Purpose of the experiment

1 . Use Spring Boot to complete asynchronous tasks, timing tasks, and email tasks.

2. Experimental content

1. Familiar with the implementation of Spring Boot integrated asynchronous tasks

2. Familiar with the implementation of Spring Boot integrated timing tasks

3. Familiar with the implementation of Spring Boot integrated mail tasks

3. Experimental steps and screenshots

1. Use Idea+Maven to create a new project and make necessary configurations.

2. Write the entry class and enable scheduled tasks.

@EnableScheduling
@SpringBootApplication
public class ChapterAsync_LWL {
    public static void main(String[] args){
        SpringApplication.run(ChapterAsync_LWL.class,args);
    }
}

3. In the service class, write a method to test the cron timing task.

//    简单的定时任务

    @Scheduled(cron = "10 * * * * *")

    public void Task01(){

        System.out.println("***********每分钟的第10S启动!*********"+simpleDateFormat.format(new Date()));

    }

4. In the service class, write a method to test the fixedDelay timing task.

//delay从第一次开始就计算间隔时间

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    int index = 1;

    @Scheduled(fixedDelay = 10000)

    public void Task02(){

        System.out.println("***********Task02任务第"+index+"启动!*********"+simpleDateFormat.format(new Date()));

        try{

            Thread.sleep(5000);

        }catch (Exception e){

            System.out.println("错误!");

        }

        System.out.println("***********Task02任务第"+index+"结束!*********"+simpleDateFormat.format(new Date()));

        index++;

    }

5. In the service class, write a method to test the fixedRate timing task.

   //rate从第一次开始就计算间隔时间

    @Scheduled(fixedRate = 10000)

    public void Task03(){

        System.out.println("***********Task03任务第"+index+"启动!*********"+simpleDateFormat.format(new Date()));

        try{

            Thread.sleep(5000);

        }catch (Exception e){

            System.out.println("错误!");

        }

        System.out.println("***********Task03任务第"+index+"结束!*********"+simpleDateFormat.format(new Date()));

        index++;

    }

6. Write the controller class, add the sendSms method, and call the service method with no return value.

 @Autowired

    AsynService asynService;

    @GetMapping("/sendSMS")

    public String sendSms() throws Exception{

        System.out.println("***********主方法开始运行***********");

        Long timeStart = System.currentTimeMillis();

        asynService.sendSMS();

        Long timeEnd = System.currentTimeMillis();

        System.out.println("***********主方法结束运行--异步调用业务逻辑耗时"+(timeEnd-timeStart)+"***********");

        return "success";

    }

@Async//无返回值的被调用方法

    public void sendSMS() throws Exception{

        System.out.println("A无返回值***********耗时的业务逻辑开始被调用***********");

        Long timeStart = System.currentTimeMillis();

        Thread.sleep(50*1000);//模拟一个耗时的操作

        Long timeEnd = System.currentTimeMillis();

        System.out.println("B无返回值***********耗时的业务逻辑结束被调用,耗时:"+(timeEnd-timeStart)+"***********");

    }

7. Write the service class to complete the asynchronous method with no return value.

    @GetMapping("/sendSMS")

    public String sendSms() throws Exception{

        System.out.println("***********主方法开始运行***********");

        Long timeStart = System.currentTimeMillis();

        asynService.sendSMS();

        Long timeEnd = System.currentTimeMillis();

        System.out.println("***********主方法结束运行--异步调用业务逻辑耗时"+(timeEnd-timeStart)+"***********");

        return "success";

    }

8. Write the controller class, add the sendCallback method, and call the service method with a return value.

 @GetMapping("/sendcb")

    public String sendCallback() throws Exception{

        System.out.println("***********主方法开始运行***********");

        Long timeStart = System.currentTimeMillis();

        Future<Integer> resultA = asynService.processA();

        Future<Integer> resultB = asynService.processB();

        Long timeEnd = System.currentTimeMillis();

        System.out.println("***********主方法结束运行--异步调用2个业务逻辑耗时"+(timeEnd-timeStart)+"***********");

        System.out.println("processA返回值:"+resultA.get()+"*****processB返回值:"+resultB.get()+"******主方法结束运行--异步调用2个业务逻辑耗时"+(timeEnd-timeStart)+"***********");

        return "success";

    }

@Async//有返回值的被调用方法

    public Future<Integer> processA() throws Exception{

        System.out.println("C有返回值***********耗时的业务逻辑开始被调用***********");

        Long timeStart = System.currentTimeMillis();

        Thread.sleep(25*1000);//模拟一个耗时的操作

        Long timeEnd = System.currentTimeMillis();

        System.out.println("D有返回值***********耗时的业务逻辑结束被调用--耗时:"+(timeEnd-timeStart)+"***********");

        return new AsyncResult<Integer>(8000);

    }

    @Async//有返回值的被调用方法

    public Future<Integer> processB() throws Exception{

        System.out.println("E有返回值***********耗时的业务逻辑开始被调用***********");

        Long timeStart = System.currentTimeMillis();

        Thread.sleep(20*1000);//模拟一个耗时的操作

        Long timeEnd = System.currentTimeMillis();

        System.out.println("F有返回值***********耗时的业务逻辑结束被调用--耗时:"+(timeEnd-timeStart)+"***********");

        return new AsyncResult<Integer>(8000);

    }

9. Write the service class and complete the asynchronous method with return value.

  @GetMapping("/sendcb")

    public String sendCallback() throws Exception{

        System.out.println("***********主方法开始运行***********");

        Long timeStart = System.currentTimeMillis();

        Future<Integer> resultA = asynService.processA();

        Future<Integer> resultB = asynService.processB();

        Long timeEnd = System.currentTimeMillis();

        System.out.println("***********主方法结束运行--异步调用2个业务逻辑耗时"+(timeEnd-timeStart)+"***********");

        System.out.println("processA返回值:"+resultA.get()+"*****processB返回值:"+resultB.get()+"******主方法结束运行--异步调用2个业务逻辑耗时"+(timeEnd-timeStart)+"***********");

        return "success";

    }

10. Test and analyze the difference between asynchronous methods with return value and asynchronous methods without return value.

The main difference between an asynchronous method with a return value and an asynchronous method without a return value is the type of the return value.

An asynchronous method without a return value generally does not return any value, and is usually used to perform some asynchronous operations without returning a result. In this type of asynchronous method, a callback function is usually used to process the result of the asynchronous operation.

Asynchronous methods with return values ​​are used to perform some computational tasks. They usually return a result, so a value type is needed to define the return value. An asynchronous method with a return value is usually called by the caller to use the interface to obtain the calculation result, or to process the result of the asynchronous operation through a callback function.

In general, an asynchronous method without a return value is suitable for performing some asynchronous operations that do not need to return a result, and an asynchronous method with a return value is suitable for performing some asynchronous operations that need to be calculated and returned. The main difference between the two is the type of the return value and how it is handled.

11. Write a scheduled task, access the Http interface of tushare, get data regularly, and test it .

public class NetRequest {

    public static JSONObject sendPost(String url,JSONObject jsonParam) throws Exception {

        OutputStream out = null;

        BufferedReader in = null;

        StringBuilder result = new StringBuilder();

        HttpURLConnection conn = null;

        try {

            // 创建url资源

            URL url_ = new URL(url);

            // 建立http连接

            conn = (HttpURLConnection) url_.openConnection();

            // 设置传递方式

            conn.setRequestMethod("POST");

            // 设置允许输入、允许输出

            conn.setDoInput(true);

            conn.setDoOutput(true);

            // 设置不用缓存

            conn.setUseCaches(false);

            //设置连接超时时间和读取超时时间

            conn.setConnectTimeout(30000);

            conn.setReadTimeout(10000);

            // 转换为字节数组

            byte[] data = (jsonParam.toString()).getBytes();

            // 设置文件长度

            conn.setRequestProperty("Content-Length", String.valueOf(data.length));

            // 设置文件类型:

            conn.setRequestProperty("contentType", "application/json");

            // 开始连接请求

            conn.connect();

            out = new DataOutputStream(conn.getOutputStream()) ;

            // 写入请求的字符串(此时jsonParam数据是放在了请求正文body里)

            out.write((jsonParam.toString()).getBytes());

            out.flush();

            out.close();

            // 请求返回的状态

            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()){

                // System.out.println("连接成功");

                // 请求返回的数据

                InputStream in1 = conn.getInputStream();

                try {

                    String readLine=new String();

                    BufferedReader responseReader=new BufferedReader(new InputStreamReader(in1,"UTF-8"));

                    while((readLine=responseReader.readLine())!=null){

                        result.append(readLine).append("\n");

                    }

                    responseReader.close();

                } catch (Exception e1) {

                    e1.printStackTrace();

                }

            } else {

                System.out.println("ResponseCode is an error code:" + conn.getResponseCode());

            }



        } catch (Exception e) {

            throw new Exception(e);

        }finally {

            try{

                if(out != null){

                    out.close();

                }

                if(in != null){

                    in.close();

                }

            }catch (IOException ioe){

                ioe.printStackTrace();

            }

        }

        return JSONObject.parseObject(result.toString());

    }

    public static void main( String[] args ) throws Exception {

        JSONObject jsonParam = new JSONObject();

        jsonParam.put("para1", "para1");

        jsonParam.put("para2", "para2");

        jsonParam.put("para3", "para3");

        String url="http://api.tushare.pro";

        JSONObject data = sendPost(url,jsonParam);

        System.out.println(data);

    }

}

//获取互联网上接口的数据
    @Scheduled(fixedRate = 60000)
    public void getFianceData() throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("api_name","trade_cal");
        jsonObject.put("token","43a324154682799b54d2a59ecbd2fc8a16a8e2949cb4fb4551277455");

        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("exchange","");
        jsonObject1.put("start_date","20180910");
        jsonObject1.put("end_date","20181001");
        jsonObject1.put("is_open","0");
        jsonObject1.put("params",jsonObject1);
        jsonObject.put("filed","exchange,cal_data,is_open,pretrade_date");
        JSONObject result = NetRequest.sendPost("http://api.tushare.pro",jsonObject);
        System.out.println(result);
    }

4. Problems encountered in the experiment and measures taken (10 points)

Error 1: {"msg": "Sorry, you do not have permission to access this interface. For details about permissions, visit: https://tushare.pro/document/1?doc_id=108.","code":40203," message":"Sorry, you do not have permission to access this interface. For details about permissions, visit: https://tushare.pro/document/1?doc_id=108."}

Troubleshooting process 1:

Check the API interface permissions: read the Tushare API interface documentation and query the relevant permission requirements of the specific interface, and confirm whether you meet the conditions for accessing the interface, such as Token permissions, calling strategies, etc.;

Update Token permissions: If you already have Token permissions, but a permission error occurs when accessing an API interface, you may need to check whether your Token permissions meet the requirements of the interface. If not, you need to re-apply to upgrade the Token permissions. You can check the Token permissions and usage on the "Personal Center" page of the Tushare platform, and update accordingly;

Contact Tushare customer service: If none of the above methods can solve the problem, you can contact Tushare customer service to ask for specific error reasons and solutions to ensure that the API interface can be accessed correctly to obtain data.

Reason Analysis 1:

This error usually means that you do not have the relevant access rights when you try to access an API interface of the Tushare platform. According to the error message, you can visit the provided link to view the specific permission requirements and access methods of the API interface.

Note: Due to the large amount of source code, friends who need it can download it in the resources, or you can private message me to get it!

Guess you like

Origin blog.csdn.net/qq_64314976/article/details/131594139