美文网首页SpringCloud教程
SpringCloud教程二: 服务消费者(rest+ribbo

SpringCloud教程二: 服务消费者(rest+ribbo

作者: 从你说谎 | 来源:发表于2018-02-06 17:18 被阅读39次

    转载请标明出处:
    http://blog.csdn.net/forezp/article/details/69788938
    本文出自方志朋的博客

    在上一篇文章,讲了服务的注册和发现。在微服务架构中,业务都会被拆分成一个独立的服务,服务与服务的通讯是基于http restful的。Spring cloud有两种服务调用方式,一种是ribbon+restTemplate,另一种是feign。在这一篇文章首先讲解下基于ribbon+rest。

    一、ribbon简介

    Ribbon is a client side load balancer which gives you a lot of control over the behaviour of HTTP and TCP clients. Feign already uses Ribbon, so if you are using @FeignClient then this section also applies.

    —–摘自官网

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

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

    • IClientConfig ribbonClientConfig: DefaultClientConfigImpl

    • IRule ribbonRule: ZoneAvoidanceRule

    • IPing ribbonPing: NoOpPing

    • ServerList ribbonServerList: ConfigurationBasedServerList

    • ServerListFilter ribbonServerListFilter: ZonePreferenceServerListFilter

    • ILoadBalancer ribbonLoadBalancer: ZoneAwareLoadBalancer

    二、准备工作

    这一篇文章基于上一篇文章的工程,启动eureka-server 工程;然后在eureka-client中加入mysql, jpa等依赖:

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    

    在application.yaml文件中加入数据库的配置:

    spring:
      application:
        name: eureka-client
      datasource:
        url: jdbc:mysql://192.168.239.234:3306/test
        username: root
        password: 123456
        driver-class-name: com.mysql.jdbc.Driver
    

    新建一个实体:

    package com.lying.eurekaclient.orm;
    
    import lombok.AllArgsConstructor;
    import lombok.Builder;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Builder
    @Entity
    public class User {
    
        @GeneratedValue
        @Id
        private Long id;
        private String name;
        private Integer age;
    
    }
    

    新建一个查询的Service:

    package com.lying.eurekaclient.service;
    
    import com.lying.eurekaclient.orm.User;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    public interface UserService extends JpaRepository<User, Long> {
    
        User findByName(String name);
    
    }
    

    新建一个controller, 如下:

    package com.lying.eurekaclient.controller;
    
    import com.lying.eurekaclient.orm.User;
    import com.lying.eurekaclient.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class UserController {
    
        @Value("${server.port}")
        private String port;
    
        @Autowired
        private UserService userService;
    
        @RequestMapping(value = "/users/{name}", method = RequestMethod.GET)
        public String fetchUserByName(@PathVariable("name") String name) {
            return userService.findByName(name).toString() + ": " + port;
        }
    
    }
    

    数据库和user表自己建

    启动eureka-client工程,它的端口为8810;将eureka-client的配置文件的端口改为8811,并启动,这时你会发现:eureka-client在eureka-server注册了2个实例,这就相当于一个小的集群。访问localhost:9999如图所示:

    三、建一个服务消费者

    重新新建一个spring-boot工程,取名为:service-ribbon;
    在它的pom.xml文件分别引入起步依赖spring-cloud-starter-eureka、spring-cloud-starter-ribbon、spring-boot-starter-web,代码如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <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.lying</groupId>
        <artifactId>ribbon-service</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <name>ribbon-service</name>
        <description>Demo project for Spring Boot</description>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.10.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>
            <spring-cloud.version>Edgware.SR2</spring-cloud.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-eureka-server</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-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>${spring-cloud.version}</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>
    
    
    </project>
    

    在工程的配置文件指定服务的注册中心地址为http://localhost:9999/eureka/,程序名称为 ribbon-service,程序端口为9910。配置文件application.yml如下:

    server:
      port: 9910
      
    spring:
      application:
        name: ribbon-service
        
    eureka:
      client:
        service-url: 
          defaultZone: http://localhost:9999/eureka/
    

    在工程的启动类中,通过@EnableDiscoveryClient向服务中心注册;并且向程序的ioc注入一个bean: restTemplate;并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能。

    package com.lying.ribbonservice;
    
    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;
    
    @SpringBootApplication
    @EnableDiscoveryClient
    public class RibbonServiceApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(RibbonServiceApplication.class, args);
        }
    
        @Bean
        @LoadBalanced
        RestTemplate restTemplate() {
            return new RestTemplate();
        }
    }
    

    写一个测试类UserService,通过之前注入ioc容器的restTemplate来消费eureka-client服务的“fetchUserByName”接口,在这里我们直接用的程序名替代了具体的url地址,在ribbon中它会根据服务名来选择具体的服务实例,根据服务实例在请求的时候会用具体的url替换掉服务名,代码如下:

    package com.lying.ribbonservice.service;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.web.client.RestTemplate;
    
    @Service
    public class UserService {
    
        @Autowired
        private RestTemplate restTemplate;
    
        public String getUserInfo(String name) {
            return restTemplate.getForObject("http://eureka-client/users/" + name, String.class);
        }
    }
    

    写一个controller,在controller中用调用UserService 的方法,代码如下:

    package com.lying.ribbonservice.controller;
    
    import com.lying.ribbonservice.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class UserController {
    
        @Autowired
        private UserService userService;
        
        @RequestMapping(value = "/getUserInfo/{name}", method = RequestMethod.GET)
        public String getUserInfo(@PathVariable("name") String name) {
            return userService.getUserInfo(name);
        }
        
    }
    

    在浏览器上多次访问http://localhost:9910/getUserInfo/Lee,浏览器交替显示:

    User(id=2, name=Lee, age=23): 8810
    User(id=2, name=Lee, age=23): 8811

    这说明当我们通过调用restTemplate.getForObject("http://eureka-client/users/" + name, String.class);方法时,已经做了负载均衡,访问了不同的端口的服务实例。

    四、此时的架构

    • 一个服务注册中心,eureka server,端口为9999
    • eureka-client工程跑了两个实例,端口分别为8810、8811,分别向服务注册中心注册
    • sercvice-ribbon端口为9910, 向服务注册中心注册
    • 当sercvice-ribbon通过restTemplate调用eureka-client的fetchUserByName接口时,因为用ribbon进行了负载均衡,会轮流的调用eureka-client:8810和8811 两个端口的fetchUserByName接口;

    源码下载:https://github.com/lyingfromyou/SpringCloudExample

    五、参考资料

    本文参考了以下:

    spring-cloud-ribbon

    springcloud ribbon with eureka

    服务消费者

    相关文章

      网友评论

        本文标题:SpringCloud教程二: 服务消费者(rest+ribbo

        本文链接:https://www.haomeiwen.com/subject/rcngzxtx.html