(010)SpringBoot下RestTemplate的使用

2018-11-02  本文已影响0人  Lindm
一、引言

在多模块开发中,难免会出现模块间的业务协作。若是直接依赖模块,极大可能会出现模块的相互依赖。为解决该问题,除使用 HttpClient远程访问接口外,可以使用RestTemplate访问rest服务,可以减少建立连接时间。

二、应用

1、配置maven依赖

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

2、注册RestTemplate
     从SpringBoot2.0开始,无法直接注入RestTemplate。

/**
 * @author lindm
 *
 * 该类的作用是提供spring配置
 * @Configuration 标识该类是一个spring配置类
 * @ComponentScan 默认扫描该包及子包下的spring的组件
 * @EnableTransactionManagement 启用事务管理
 * @EnableAutoConfiguration 启用spring boot的自动配置
 */
@Configuration
@ComponentScan
@EnableTransactionManagement
@EnableAutoConfiguration
public class DemoConfiguration {
    public static void main(String[] args) {
        SpringApplication.run(DocBusinessConfiguration.class, args);
    }

    @Bean
    RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
        return restTemplateBuilder
                .setConnectTimeout(5000) //单位ms, 设置连接时间,避免线程过多被阻塞挂起,导致整个系统宕机
                .setReadTimeout(5000)
                .build();
    }
}

3、编写API发送请求

package com.external.service.impl;

import com.external.service.DisToOthersMng;
import com.utils.exception.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * 测试类
 *
 * @author lindm
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class DisToOther{

    /**
    * 注入restTemplate
    */
    @Resource
    private RestTemplate withTokenRestTemplate;

    public boolean disToOthers(String type, String docId) {
        HashMap<String, Object> map;
        boolean result, fianl = true;
     
        switch (type) {
            case "archive":
                map = this.getToArchiveHashMap(docId);
                String url = "http://127.0.0.1:8080/archive/insertArchive";
                // 发送post请求,请求参数map,返回boolean类型值 
                result = this.withTokenRestTemplate.postForObject(url, map, boolean.class);
                if (!result) {
                    fianl = false;
                }
                break;
            default:
                break;
        }
        return fianl;
    }
}
四、参考地址

1、链接地址: https://www.jianshu.com/p/c96049624891

上一篇下一篇

猜你喜欢

热点阅读