Spring-Cloud学习笔记(二)RestTemplate和Feign的使用方式以及部分注解的使用

通常,我们在搭建springcloud微服务架构时,会把我们的服务注册到高可用eureka服务注册发现中心上面,各个服务之间的通信就是无可避免的,此时我们就需要用到RestTemplate 或者Feign去进行各个服务之间的通信调用。

                                   RestTemplate的三种使用方式

1、直接只用RestTemplate 方式调用,url写死。

  String  msg =restTemplate.getForObject("http://localhost:8080/server/msg",String.class);

2、利用 loadBalancerClient 通过应用名(spring.application.name或者在eureka注册中心页面可以看到此名称)获取 url,然后在使用restTemplate

    @Autowired
    private LoadBalancerClient loadBalancerClient;


    String  url = String.format("http://%s:%s/",serviceInstance.getHost(),serviceInstance.getPort())+"server/msg";
    msg =  restTemplate.getForObject(url,String.class);
    log.info("获取的msg为{}",msg);

3、方式三(利用@LoadBalanced注解,可在restTemplate中使用应用名字的方式去调用url)

@Component
public class RestTemplateConfig {

       @Bean
       @LoadBalanced
       public RestTemplate  restTemplate(){
           return new RestTemplate();
       }

}

或者
 @Autowired
 @LoadBalanced
 private RestTemplate restTemplate;


String  msg  = restTemplate.getForObject("http://PRODUCT/server/msg",String.class);

spring-cloud 中的负载均衡器rabbion,默认是轮询机制,可以通过以下方式更改为随机负载均衡机制。

PRODUCT: #应用的Application名称
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule  

                                                      Feign的使用方式

添加依赖

<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-feign</artifactId>
			<version>1.4.5.RELEASE</version>
		</dependency>

在启动类上面添加@EnableFeignClients注解

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.example.order.client")  #指定远程调用的服务的包名
public class OrderApplication {

	public static void main(String[] args) {
		SpringApplication.run(OrderApplication.class, args);
	}
}

编写代码

package com.example.order.client;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * 指定应用名称
 */
@FeignClient(name = "product")
public interface ProductClient {

          @GetMapping("/server/msg")
          String getMsg();

}

调用服务

  @Autowired
   private ProductClient productClient;

   msg = productClient.getMsg();
   return  msg;

Feign采用声明式REST客户端(伪rpc)采用了基于接口的注解

,本质还是http客户端,通过feign能够对远程调用对于开发者完全透明,得到与调用本地方法一致的编码体验。

猜你喜欢

转载自blog.csdn.net/qq_31905135/article/details/81171805
今日推荐