spring cloud快速入门教程(五)进程间调用和微服务负载均衡(RestTemplate+Ribbon)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tang86100/article/details/78895452

前面的2~4章就可以基本上搭起一个微服务框架了,前端就可以使用我们提供的各项服务了,但是有些复杂逻辑需要多个服务进程间相互调用这要怎么办?spring cloud提高了两种方案,一种是基于http请求的RestTemplate,另一种是类似于RPC框架的基于tcp的feign(和dubbo的方式类似),他们两个都集成了微服务的负载均衡工具Ribbon,可以达到以下效果:


先说说RestTemplate,我们修改一下之前的userService那个module,引入依赖包

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
主程序代码改成如下内容:

package com.tzy;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient

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

    @Bean
    @LoadBalanced
    RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
@Bean会创建一个被spring管理的对象

@LoadBalance会启动Ribbon

创建一个Service测试一下RestTemplate的使用,远程调用一下service-product微服务,自己在service-product里写一个getProduct的方法,返回一定内容。

package com.tzy.userService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class GetProductService {
    @Autowired
    RestTemplate restTemplate;

    public String getGoods(){
        return restTemplate.getForObject("http://service-product/getProduct",String.class);
    }
}

注意:

getForObject里第一个参数是请求微服务的地址和资源,因为微服务在Eureka中注册过了,可以直接那么写,第二个参数是返回值类型;


结果肯定是成功的啦,风格是不是很接近http请求呢。

猜你喜欢

转载自blog.csdn.net/tang86100/article/details/78895452
今日推荐