在SpringBoot项目中,RestTempplate是替代HttpClient的存在,它的功能十分强大,而我们SpringCloud微服务之间的调用,最简单的方法就是通过RestTemplate来调用。
要想使用RestTemplate,那首先需要注入它,具体代码如下:
package com.mazong.serverblogarticle;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class ServerBlogArticleApplication {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ServerBlogArticleApplication.class, args);
}
}
在ArticleController类的接口中,我们来演示一下RestTemplate的使用方法,具体代码如下:
package com.mazong.serverblogarticle.controller;
import com.mazong.serverblogarticle.entity.TbArticle;
import com.mazong.serverblogarticle.mapper.IDbArticleMapper;
import com.mazong.serverbloguser.entity.TbUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/")
public class ArticleController {
@Autowired
private IDbArticleMapper iDbArticleMapper;
@Autowired
HttpServletRequest request;
@Autowired
RestTemplate restTemplate;
@RequestMapping(value = "/getArticle")
@ResponseBody
public Object getArticle(@RequestParam("id") Integer id) {
// http://localhost:9000/getArticle?id=2
Map<String, Object> resultMap = new HashMap<>();
TbArticle article = iDbArticleMapper.getArticle(id);
resultMap.put("article", article);
if(article != null) {
TbUser user = restTemplate.getForObject("http://localhost:8000/getUser?id="+article.getUid(), TbUser.class);
resultMap.put("user", user);
}
return resultMap;
}
}
<!-- 引入TbUser类的包 -->
<dependency>
<groupId>com.mazong</groupId>
<artifactId>server-blog-user</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
注意:由于server-blog-article服务依赖于server-blog-user服务,所以要先启动user服务,然后再启动article服务。