首页 > 其他分享 >接口、定时、异步

接口、定时、异步

时间:2023-05-29 22:55:07浏览次数:37  
标签:异步 String System 接口 new println path 定时 out

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";
    }

标签:异步,String,System,接口,new,println,path,定时,out
From: https://www.cnblogs.com/jh0129/p/17441941.html

相关文章

  • C# 异步编程(await、async&Task)
    视频链接:.NET6教程,.NetCore2022视频教程,杨中科主讲_哔哩哔哩_bilibili异步编程为什么要异步编程?几个误区:(1)异步不一定能提高效率(2)异步不是多线程传统多线程异步开发太麻烦。C#关键字:async、await。【async、await不等于“多线程”】async、await的基本使用“异步方法”:......
  • 【Java】你真的了解抽象类和接口?
    一、抽象类在Java中,一个类如果被abstract修饰称为抽象类,抽象类中被abstract修饰的方法称为抽象方法**,抽象方法不用给出具体的实现体**。publicclassTestDemo{publicstaticvoidmain(String[]args){Circlec=newCircle();c.setR(5);c.......
  • 为什么我们需要API接口?API接口的核心又是什么?
    ​    API(ApplicationProgrammingInterface)是一种连接不同软件之间的标准化的接口,可以让不同软件间进行数据交互和通信。API接口的作用很多,以下是几个主要的原因:1.提高软件系统的灵活性和可扩展性。API接口可以将不同的模块分离开来,使得系统更加模块化,便于后续的扩展......
  • Linux下C++实现一个定时器
    要在Linux下实现一个定时器,可以使用以下两种方法:使用系统提供的定时器APILinux系统提供了一些定时器API,如setitimer、timer_create、timer_gettime等,可以使用这些API来实现定时器。以setitimer为例,可以按照以下步骤来使用:1.定义一个itimerval结构体变量,该结构体包含定时器的初......
  • 接口注意事项
          ......
  • 从JDK.8开始接口新增的方法
        ......
  • 接口:综合案例
    packagecom.Demo4;publicclassTest{publicstaticvoidmain(String[]args){//目标:完成学生信息管理的实例ClassManageclassManage=newClassManage();classManage.printInfo();classManage.printScore();}}package......
  • 接口
        ......
  • mysql、sqlserver、oracle分页,java分页统一接口实现
    定义:pageStart起始页,pageEnd终止页,pageSize页面容量oracle分页:rownum numfrom(实际传的SQL)where rownum<=pageEnd)wherenum>=pageStartsqlServer分页:           select*from(select top 页面容量from(select top字段Adesc)astemptable2orderb......
  • Python generator 构建协程,实现异步编程(使用yield构建消息处理者和消息创造者)
    协程的定义理解Python协程可以在单个处理机或多个处理机上运行,这取决于具体实现方式。在Python中,主要有两种协程实现方式:生成器协程和asyncio协程。生成器协程只能在单个处理机上运行,因为生成器协程是通过生成器函数实现的,而生成器函数在单个线程中执行。生成器协程也称为......