RestTemplate调用服务接口
主应用类配置
在项目src/main/java下创建主应用类 ConsumerOrderApplication.java,添加eureka服务端注解@EnableEurekaServer和@SpringBootApplication
@EnableEurekaClient
@SpringBootApplication
public class ConsumerOrderApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerOrderApplication.class, args);
}
}
RestTemplate配置
创建配置类ApplicationContextConfig,并指定用于返回RestTemplate的bean。注解@LoadBalanced用于在调用微服务接口时进行负载均衡。
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
RestTemplate getRestTemplate(){
//return new RestTemplate();
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(5000);// 设置超时 毫秒
requestFactory.setReadTimeout(10000);
return new RestTemplate(requestFactory);
}
}
controller层调用
在controller层可以通过RestTemplate进行微服务接口调用,使用方法如下:
@RestController
@RequestMapping("/order")
public class OrderController {
@Resource
private RestTemplate restTemplate;
private final String PAYMENT_URL = "http://PAYMENT-SERVER";
@PostMapping("/create")
CommentResult<Integer> create(@RequestBody Payment payment){
return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommentResult.class);
}
@GetMapping("/get/{id}")
CommentResult<Payment> getById(@PathVariable(name = "id") Long id) {
return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommentResult.class);
}
}
RestTemplate请求头数据传递json数据
//注入RestTemplate实例
@Autowired
private RestTemplate restTemplate;
//下面是发送json的用法
private AppResult doSendAppMsg(String msgJson) {
AppResult appResult;
HttpHeaders headers = new HttpHeaders();
//请求头数据传递json数据
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);//设置json
HttpEntity<String> requestEntity = new HttpEntity<>(msgJson, headers);//将json放到httpEntity
String url = weChatWorkUrlProps.getAppMsgSend() + "?access_token=" + wctTokenCache;
//调用接口
ResponseEntity<AppResult> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, new ParameterizedTypeReference<AppResult>() {});
appResult = responseEntity.getBody();
return appResult;
Spring Cloud使用Feign调用服务接口
使用Spring Cloud Feign
创建一个SpringBoot工程,作为服务调用方
1.pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
spring-cloud-starter-feign加入了feign的依赖
2.启动类
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class FeignConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(FeignConsumerApplication.class, args);
}
}
@EnableFeignClients:开启Spring Cloud Feign的支持功能
3.服务层
package com.local.springboot.client.clientcustomer.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(value = "client-provider-server", path = "/api", fallback = MyFeignFallback.class)
public interface MyFeign {
@GetMapping("/user/{id}")
String getUser(@PathVariable("id") String id);
}
client-provider-server是服务提供者在eureka注册的名字,也可以直接指定url
@FeignClient(name = “client-provider-server”, path = “/api”,url = “http://localhost:8081”)
url可以直接指定第三方服务地址,path指定路径,接口的方法指定接口
4.controller调用接口
/**
* feign远程调用
*/
@GetMapping("/query/{id}")
public String getUser(@PathVariable(value = "id") String id) {
return myFeign.getUser(id);
}
/**
* feign远程调用
*/
@GetMapping("/exception")
public String exception() {
return myFeign.exception();
}
5.服务提供者Controller层
@RestController
@RequestMapping("api")
public class ProviderController {
@GetMapping("/user/{id}")
public String user(@PathVariable(value = "id") String id) {
return "我是服务提供者==>用户id:" + id;
}
}
6.Fallback熔断
package com.local.springboot.client.clientcustomer.feign;
import org.springframework.stereotype.Component;
/**
* feign调用容错处理
*/
@Component
public class MyFeignFallback implements MyFeign {
@Override
public String getUser(String id) {
return null;
}
@Override
public String exception() {
return "网络请求超时,请稍后重试!";
}
}
7.feign请求头数据传递
方案一
通过@RequestHeader(name = “name”)
@FeignClient(name = "service-name")
public interface XXXFeignClient {
@RequestMapping(value = "/user/getUserTicket", method = RequestMethod.GET)
String getUserTicket(@RequestParam("id") String id, @RequestHeader(name = "Referer") String referer);
}
然后在调用的时候将referer参数传递进去即可,如
public String getTicketById(@RequestParam("id") String id, HttpServletRequest request) {
String referer = request.getHeader("Referer");
return xxxFeignClient.getUserTicket(id, referer);
}
方案二
/**
* @Classname FeignClientInterceptor
* @Description 给feign进行拦截和自定义的处理
*/
@Component
public class FeignClientInterceptor implements RequestInterceptor {
/**
* @Description 拦截feign进行拦截,并在请求头添加,需要添加的header参数
*/
@Override
public void apply(RequestTemplate requestTemplate) {
requestTemplate.header("tenantId","模拟数据");
System.out.println("--------------测试数据----------------");
System.out.println(requestTemplate.request());
System.out.println(requestTemplate);
System.out.println("----------------测试数据--------------");
}
}
8.Feign超时时间设置
feign:
client:
config:
default:
connectTimeout: 3000
readTimeout: 6000