Ribbon负载均衡及Feign消费者调用服务

1、ribbon集成eureka完成服务调用

Ribbon是什么?
Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法,将Netflix的中间层服务连接在一起。Ribbon客户端组件提供一系列完善的配置项如连接超时,重试等。简单的说,就是在配置文件中列出Load Balancer(简称LB)后面所有的机器,Ribbon会自动的帮助你基于某种规则(如简单轮询,随即连接等)去连接这些机器。我们也很容易使用Ribbon实现自定义的负载均衡算法。
Ribbon负载均衡及Feign消费者调用服务_第1张图片
加入pom.xml依赖,加入 ribbon相关依赖



    org.springframework.cloud
    spring-cloud-starter-eureka


    org.springframework.cloud
    spring-cloud-starter-ribbon


    org.springframework.cloud
    spring-cloud-starter-config

yml文件

server:
  context-path: /
  port: 80
eureka:
  client:
    service-url:
      defaultZone: http://eureka2001.xhh.com:2001/eureka/,http://eureka2002.xhh.com:2002/eureka/,http://eureka2003.xhh.com:2003/eureka/
    register-with-eureka: false

SpringCloudConfig

package com.xhh.microservicestudentconsumer80.config;

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 SpringCloudConfig {
    @LoadBalanced  // 引入ribbon负载均衡
    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

因为和eureka整合,所以启动类StudentConsumerApplication_80 加个注解 @EnableEurekaClient

我们的微服务应用名称是 microservice-student
所以服务调用者这边的控制器里PRE_HOST改成 http://MICROSERVICE-STUDENT即可;

先启动三个eureka,然后再启动服务提供者,再启动服务消费者;
执行这个http://localhost:1001/student/list
在这里插入图片描述

2、ribbon负载均衡

pom依赖



    4.0.0
    
        com.xhh
        springcloud
        1.0-SNAPSHOT
    

    microservice-student-provider


    
        
            com.xhh
            microservice-common
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            mysql
            mysql-connector-java
        
        
            org.springframework.boot
            spring-boot-starter-tomcat
        
        
            com.alibaba
            druid-spring-boot-starter
        
        
        
            org.springframework
            springloaded
        
        
            org.springframework.boot
            spring-boot-devtools
        
        
            com.xhh
            microservice-common
            1.0-SNAPSHOT
            compile
        
        
        
            org.springframework.cloud
            spring-cloud-starter-eureka
        
        
            org.springframework.cloud
            spring-cloud-starter-config
        
        
        
            org.springframework.boot
            spring-boot-starter-actuator
        

    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


yml文件

---
server:
  port: 1001
  context-path: /
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/xhh?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  application:
    name: microservice-student
  profiles: provider-1001

eureka:
  instance:
    hostname: localhost
    appname: microservice-student
    instance-id: microservice-student:1001
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://eureka2001.xhh.com:2001/eureka/,http://eureka2002.xhh.com:2002/eureka/,http://eureka2003.xhh.com:2003/eureka/

info:
  groupId: com.xhh.springcloud
  artifactId: microservice-student-provider-1001
  version: 1.0-SNAPSHOT
  userName: http://xhh.com
  phone: 123456

---
server:
  port: 1002
  context-path: /
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/xhh?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  application:
    name: microservice-student
  profiles: provider-1002

eureka:
  instance:
    hostname: localhost
    appname: microservice-student
    instance-id: microservice-student:1002
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://eureka2001.xhh.com:2001/eureka/,http://eureka2002.xhh.com:2002/eureka/,http://eureka2003.xhh.com:2003/eureka/

info:
  groupId: com.xhh.springcloud
  artifactId: microservice-student-provider-1002
  version: 1.0-SNAPSHOT
  userName: http://xhh.com
  phone: 123456

---
server:
  port: 1003
  context-path: /
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/xhh?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  application:
    name: microservice-student
  profiles: provider-1003

eureka:
  instance:
    hostname: localhost
    appname: microservice-student
    instance-id: microservice-student:1003
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://eureka2001.xhh.com:2001/eureka/,http://eureka2002.xhh.com:2002/eureka/,http://eureka2003.xhh.com:2003/eureka/

info:
  groupId: com.xhh.springcloud
  artifactId: microservice-student-provider-1003
  version: 1.0-SNAPSHOT
  userName: http://xhh.com
  phone: 123456

Ribbon负载均衡及Feign消费者调用服务_第2张图片

3、feign集成ribbon调用

pom依赖



    org.springframework.cloud
    spring-cloud-starter-feign

StudentClientService接口

package com.xhh.microservicecommon.service;


import com.xhh.microservicecommon.entity.Student;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * Student Feign接口客户端
 * @author Administrator
 *
 */
@FeignClient(value="MICROSERVICE-STUDENT")
public interface StudentClientService {
 
    /**
     * 根据id查询学生信息
     * @param id
     * @return
     */
    @GetMapping(value="/student/get/{id}")
    public Student get(@PathVariable("id") Integer id);
     
    /**
     * 查询学生信息
     * @return
     */
    @GetMapping(value="/student/list")
    public List list();
     
    /**
     * 添加或者修改学生信息
     * @param student
     * @return
     */
    @PostMapping(value="/student/save")
    public boolean save(Student student);
     
    /**
     * 根据id删除学生信息
     * @return
     */
    @GetMapping(value="/student/delete/{id}")
    public boolean delete(@PathVariable("id") Integer id);

    @RequestMapping("/student/ribbon")
    public String ribbon();
}

2、新建一个Feign消费者项目
建一个microservice-student-consumer-feign-80



    4.0.0
    
        com.xhh
        springcloud
        1.0-SNAPSHOT
    

    microservice-student-consumer-feign-80

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
        
            org.springframework.cloud
            spring-cloud-commons
            1.3.4.RELEASE
            compile
        
        
            org.springframework
            spring-web
            5.2.1.RELEASE
            compile
        
        
            org.springframework
            spring-web
            5.2.1.RELEASE
            compile
        
        
            com.netflix.ribbon
            ribbon-loadbalancer
            2.2.5
            compile
        
        
            org.springframework.cloud
            spring-cloud-netflix-core
            1.4.5.RELEASE
            compile
        
        
            org.springframework.cloud
            spring-cloud-netflix-eureka-client
            1.4.5.RELEASE
            compile
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


SpringCloudConfig

package com.xhh.microservicestudentconsumerfeign80.config;


import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RetryRule;
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 SpringCloudConfig {

    @LoadBalanced  // 引入ribbon负载均衡
    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

    /**
     * 自定义调用规则(服务提供者掉线后不再调用,解决轮询问题)
     * @return
     */
    @Bean
    public IRule myRule(){
        return new RetryRule();
    }
}

MicroserviceStudentConsumerFeign80Application

package com.xhh.microservicestudentconsumerfeign80;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

@EnableEurekaClient
@EnableFeignClients(value = "com.xhh.*.*")
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class MicroserviceStudentConsumerFeign80Application {

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

}

StudentConsumerController

package com.xhh.microservicestudentconsumerfeign80.conterller;


import com.xhh.microservicecommon.entity.Student;
import com.xhh.microservicecommon.service.StudentClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentConsumerController {

    @Autowired
    private StudentClientService studentClientService;

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping(value = "/save")
    private boolean save(Student student) {
        return studentClientService.save(student);
    }

    @GetMapping(value = "/list")
    public List list() {
        return studentClientService.list();
    }

    @GetMapping(value = "/get/{id}")
    public Student get(@PathVariable("id") Integer id) {
        return studentClientService.get(id);
    }

    @GetMapping(value = "/delete/{id}")
    public boolean delete(@PathVariable("id") Integer id) {
        try {
            studentClientService.delete(id);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @RequestMapping("/ribbon")
    public String ribbon(){
        return studentClientService.ribbon();
    }
}

Ribbon负载均衡及Feign消费者调用服务_第3张图片

你可能感兴趣的:(Ribbon负载均衡及Feign消费者调用服务)