说明
RestTemplate
ums中的controller,用 RestTemplate 作为 web client,调用 notice 微服务
关于 RestTemplate介绍参见:
https://www.malaoshi.top/show_1EF5grJlvJii.html
修改ums工程配置类
通过配置类管理RestTemplate实例
必须使用配置类,后面要用到负载均衡
创建配置类
改写配置类
package top.malaoshi.ums.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ApplicationContextConfig {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
实现controller类
ums工程实现controller类
编写代码
package top.malaoshi.ums.controllers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import top.malaoshi.ums.entities.Notice;
import top.malaoshi.ums.json.CommonResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@RestController
@Slf4j
public class FollowController {
public static final String NOTICE_URL="http://localhost:8001";
@Resource
private RestTemplate restTemplate;
@PostMapping(value="/follow")
public CommonResult follow(Notice notice){
return restTemplate.postForObject(NOTICE_URL+"/sendNotice/",notice, CommonResult.class);
}
@GetMapping(value="/getNotice/{id}")
public CommonResult getNotice(@PathVariable("id") String id){
return restTemplate.getForObject(NOTICE_URL+"/getNoticeById/"+id, CommonResult.class);
}
@GetMapping(value="/getNotice2/{id}")
public CommonResult getNotice2(@PathVariable("id") String id){
log.info("---"+id);
ResponseEntity<CommonResult> re=restTemplate.getForEntity(NOTICE_URL+"/getNoticeById/{1}", CommonResult.class,id);
if(re.getStatusCode().is2xxSuccessful()){
return re.getBody();
}else {
return new CommonResult(-1,"失败!");
}
}
}


