RestTemplate、Feign调用服务接口,自定义超时、请求头数据传递

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 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

橘右今

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值