SpringCloud 学习实战(二)--服务消费restful+ribbon

接上一篇,在实际开发中,微服务架构通常会根据实际业务分不同的服务独立部署,服务与服务之间通过restful进行通讯。Spring cloud有两种服务调用方式,一种是ribbon+restTemplate,另一种是feign。这一篇文章首先讲解下基于ribbon+rest

1. Ribbon简介

ribbon是一个负载均衡客户端,可以很好的控制htttcp的一些行为。Feign默认集成了ribbon

ribbon 已经默认实现了这些配置bean

  • IClientConfig ribbonClientConfig: DefaultClientConfigImpl
  • IRule ribbonRule: ZoneAvoidanceRule
  • IPing ribbonPing: NoOpPing
  • ServerList ribbonServerList: ConfigurationBasedServerList
  • ServerListFilter ribbonServerListFilter: ZonePreferenceServerListFilter
  • ILoadBalancer ribbonLoadBalancer: ZoneAwareLoadBalancer

2. 再添加一个eureka client

你可以选择新建一个项目,也可以将上一篇中eurekaclient 项目先跑起来,然后修改application.yml中的端口号为8763,再重新跑一次main方法,这样就相当于有两个服务了。

访问http://localhost:8761/ 如下图:

发现已经注册了两个服务。


3. 搭建ribbon服务消费者

3.1 新建项目eurekaribbon  pom文件如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.yuanyuan</groupId>
  <artifactId>eurekacribbon</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>eurekacribbon</name>
  <description>Demo project for Spring Boot</description>
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

3.2 application.yml文件如下:

指定自己的服务注册中心的地址

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8764
spring:
  application:
    name: service-ribbon

3.3 启动类如下:

注入RestTemplate ,通过@LoadBalanced 注解,表明该RestTemplate 开启负载均衡功能。

package com.yuanyuan;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/**
 * Hello world!
 *
 */
@SpringBootApplication
@EnableDiscoveryClient
public class EurekaribbonApplication 
{
    public static void main( String[] args )
    {
        SpringApplication.run(EurekaribbonApplication.class, args);
    }
    
   @Bean // 注入RestTemplate
   @LoadBalanced // 开启负载均衡
   RestTemplate restTemplate() {
	   return new RestTemplate();
   }
}

3.4 新建service,代码如下:

通过RestTemplate 的方法调用服务接口,用服务名称代替url,在ribbon中会根据服务名称找到对应的服务实例,根据服务实例在请求的时候会用具体的url替换掉服务名。

package com.yuanyuan.eurekaservice;

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

@Service
public class HelloService {
	
	@Autowired
	RestTemplate restTemplate;
	
	public String sayHi(String name) {
		return restTemplate.getForObject("http://service-hi/hi?name=" + name, String.class);
	}

}

3.5 新建controller,代码如下:

package com.yuanyuan.eurekacontroller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.yuanyuan.eurekaservice.HelloService;

@RestController
public class HelloController {
	
	@Autowired
	private HelloService helloService;
	
	@RequestMapping("/hi")
	public String sayHi(@RequestParam String name) {
		return helloService.sayHi(name);
	}

}
tips:

application启动类的目录要包含service和controller,不然启动之后会加载不是相应的内容。

访问http://localhost:8764/hi?name=yuanyuan

多次刷新会发现87628763端口会交替出现,说明ribbon在调用服务的时候已经实现了负载均衡。




猜你喜欢

转载自blog.csdn.net/yinghuacao_dong/article/details/79963995