接口、定时、异步

1 远程接口

1.1 URL与HttpUrlConnection

//接口路径
     String path = "";
//创建URL
     URL url = new URL(path);
//连接
     HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//开始连接
     urlConnection.connect();
//获取字节流
     InputStream inputStream = urlConnection.getInputStream();
//把数据转换为字符串
     byte[] bytes = new byte[inputStream.available()];
     inputStream.read(bytes);
     String s = new String(bytes);
     System.out.println(s);
//json字符串转对象
     JSONObject jsonObject = JSON.parseObject(s);
     Object code = jsonObject.get("code");
     if (code.equals(200)) {
         JSONObject result = jsonObject.getJSONObject("result");
         Object content = result.get("content");
         System.out.println(content);
      }
//JSON转对象需要的依赖	
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.83</version>
    </dependency>

1.2 apache的HttpClient

//apache的HttpClient要用的依赖
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.6</version>
    </dependency>

1.2.1 GET请求

//接口路径	
	String path = "";
//创建发送请求的客户端
        CloseableHttpClient hc = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(path);
//设置请求头(防止TCP状态一直保持在CLOSE_WAIT,在请求头中进行Connection配置)
        httpGet.setHeader("connection", "close");
//获取返回结果
        HttpResponse response = hc.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            String s = EntityUtils.toString(entity);
            System.out.println(s);
//关闭资源            
           EntityUtils.consume(entity);
        }
//关闭资源
        httpGet.abort();
        hc.close();

1.2.2 POST请求

//接口路径	        
	String path = "";
        CloseableHttpClient hc = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(path);
//设置请求头
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("Connection", "close");
//post请求的参数
        HashMap<String, String> map = new HashMap<>();
        map.put("phone", "13213785063");
        map.put("code", "123456");
// 设置请求体内容
        String s = JSON.toJSONString(map);
        httpPost.setEntity(new StringEntity(s));
// 执行
        HttpResponse response = hc.execute(httpPost);
        System.out.println(response);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            String data = EntityUtils.toString(entity);
            System.out.println(data);
            EntityUtils.consume(entity);
        }
        httpPost.abort();
     hc.close();

1.2.3 PUT请求

参考 1.2.2 POST请求

1.2.4 DELETE请求

参考 1.2.1 GET请求

1.3 spring的RestTemplate

1.3.1 GET请求

    RestTemplate restTemplate = new RestTemplate();
//接口路径
    String path="";
//所有响应信息
    ResponseEntity<String> forEntity = restTemplate.getForEntity(path, String.class);
    System.out.println(forEntity);
//响应体信息
    String forObject = restTemplate.getForObject(path, String.class);
    System.out.println(forObject);

1.3.2 POST请求

     RestTemplate restTemplate = new RestTemplate();
//接口路径
     String path="";
     User user = new User("张三", 18);
//所有响应信息
     ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(path, user, String.class);
     System.out.println(stringResponseEntity);

1.3.3 PUT请求

     RestTemplate restTemplate = new RestTemplate();
//接口路径
     String path="";
     HashMap<String, Object> map = new HashMap<>();
     map.put("userName","张三");
     map.put("age",18);
     restTemplate.put(path,map);

1.3.4 DELETE请求

     RestTemplate restTemplate = new RestTemplate();
//接口路径
     String path="http://localhost:8080/delete/{0}";
     restTemplate.delete(path,"1,2,3,4");

1.3.5 复杂请求

    RestTemplate restTemplate = new RestTemplate();
    String path="http://localhost:8080/delete/{0}";
//设置请求头
    HttpHeaders headers = new HttpHeaders();
//设置token
    headers.add("token","");

    HttpEntity httpEntity = new HttpEntity(headers);
    ResponseEntity<String> exchange = restTemplate.exchange(path, HttpMethod.DELETE, httpEntity, String.class, "1,3.5");
    System.out.println(exchange.getStatusCode());
    System.out.println(exchange.getHeaders());
    System.out.println(exchange.getBody());

2 定时

2.1 Timer

  • 定义类继承TimerTask类,重写run方法

2.2 spring-task

<!--    开启定时任务注解驱动-->
    <task:annotation-driven/>
在方法上添加注解@Scheduled(cron = "0/5 * * * * ?")
    
    @Scheduled(cron = "0/5 * * * * ?")
    public void test(){
        System.out.println("123465");
    }
  • springtask默认多个任务之间使用的是同一个线程是同步的。一个任务如果有耗时操作,会影响另一个任务。

  • @Async注解可以保证任务每次都是按照cron表达式的时间执行,因为每次都是开启新的线程。

  • 也可以使用配置的方式,让一个任务分配一条线程去执行。

<!-- size默认1个 -->    
	<task:scheduler id="taskScheduler" pool-size="2"></task:scheduler>

<!-- 指定通过taskScheduler任务调度线程池来对指定的任务按照各自的cron表达式执行   -->
    <task:scheduled-tasks scheduler="taskScheduler">
        <task:scheduled ref="Test" method="test1" cron="0/5 * * * * ?"/>
        <task:scheduled ref="Test" method="test2" cron="0/10 * * * * ?"/>
    </task:scheduled-tasks>

2.3 quartz组件

  • 可百度配置xml

3 异步任务

<!--    配置线程池对象-->
    <bean class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!--        核心线程数-->
        <property name="corePoolSize" value="10"></property>
<!--        最大线程数量-->
        <property name="maxPoolSize" value="100"></property>
<!--        空闲线程的闲置时间-->
        <property name="keepAliveSeconds" value="20"></property>
<!--        等待队列的容量-->
        <property name="queueCapacity" value="100"></property>
<!--        拒绝策略(等待队列满了,直接在主线程上执行)-->
        <property name="rejectedExecutionHandler">
            <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy"></bean>
        </property>
    </bean>
  • 定义一个类提供异步任务的方法
	public static Runnable test(String name, String age) {
        return new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "----邮件");
            }
        };
    }
  • 提供任务管理类,执行异步任务
    @Component
    public class TestManger {
        @Autowired
        private ThreadPoolTaskExecutor threadPoolTaskExecutor;
        public void execute (Runnable a){
            threadPoolTaskExecutor.execute(a);
        }
    }
  • 测试
    @GetMapping("test")
    @ResponseBody
    public String sendEmail(){
        asyncManger.execute(TestFactory.test("111",222));
        System.out.println("主线程");
        return "success";
    }
posted @ 2023-05-29 22:51  VIoleng  阅读(32)  评论(0)    收藏  举报