一、引言
在多模塊開發(fā)中果覆,難免會(huì)出現(xiàn)模塊間的業(yè)務(wù)協(xié)作。若是直接依賴模塊畴栖,極大可能會(huì)出現(xiàn)模塊的相互依賴随静。為解決該問題,除使用 HttpClient遠(yuǎn)程訪問接口外吗讶,可以使用RestTemplate訪問rest服務(wù)燎猛,可以減少建立連接時(shí)間。
二照皆、應(yīng)用
1重绷、配置maven依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2、注冊(cè)RestTemplate
?????從SpringBoot2.0開始膜毁,無法直接注入RestTemplate昭卓。
/**
* @author lindm
*
* 該類的作用是提供spring配置
* @Configuration 標(biāo)識(shí)該類是一個(gè)spring配置類
* @ComponentScan 默認(rèn)掃描該包及子包下的spring的組件
* @EnableTransactionManagement 啟用事務(wù)管理
* @EnableAutoConfiguration 啟用spring boot的自動(dòng)配置
*/
@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, 設(shè)置連接時(shí)間,避免線程過多被阻塞掛起瘟滨,導(dǎo)致整個(gè)系統(tǒng)宕機(jī)
.setReadTimeout(5000)
.build();
}
}
3候醒、編寫API發(fā)送請(qǐng)求
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;
/**
* 測(cè)試類
*
* @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";
// 發(fā)送post請(qǐng)求,請(qǐng)求參數(shù)map,返回boolean類型值
result = this.withTokenRestTemplate.postForObject(url, map, boolean.class);
if (!result) {
fianl = false;
}
break;
default:
break;
}
return fianl;
}
}
四杂瘸、參考地址
1倒淫、鏈接地址: http://www.reibang.com/p/c96049624891