第六章 Spring Cloud 自定义Ribbon的负载均衡(java配置)

官网:http://cloud.spring.io/spring-cloud-static/Dalston.SR2/#spring-cloud-ribbon

项目结构如下:



AutoConfiguration类:

package com.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;

/**
 * 通过自定义配置Ribbon,这样的话:两个服务既可以通过ribbon调用服务,又可以按照随机规则调用服务,此时就要:此类不要放在与启动类能扫到的包下,不然会报警告,官网有说明
 *
 */

@Configuration	//表示是配置类
//@ExcludeFromComponentScan //此注解是爸自定义配置的AutoConfiguration类放到启动类能扫描到的包才需要
public class AutoConfiguration {

/***   注意:若是把AutoConfiguration类放到启动类能扫描到的包下,那么要用注释掉的代码,把没有注释掉的进行去掉   ,此时还要增加一个接口*/	
	
	
/*	
 	//随机请求服务规则:对于负载均衡来说
	@Bean
	public IRule ribbonRule() {
		return new RandomRule();
	}*/
	
	
	@Autowired
	IClientConfig config;
	
	//随机请求服务规则:对于负载均衡来说
	@Bean
	public IRule ribbonRule(IClientConfig config) {
		return new RandomRule();
	}
	
	
}

OrderController

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.example.demo.entity.User;

@RestController
public class OrderController {
	
	  @Autowired
	  private RestTemplate restTemplate;
	  
	  @Autowired
	  private LoadBalancerClient loadBalancerClient;

	  @GetMapping("/order/{id}")
	  public User findById(@PathVariable Long id) {
	    // http://localhost:7900/user/
	    // VIP virtual IP(http://localhost:7900/user/表示虚拟ip)
	    // HAProxy Heartbeat
	    return this.restTemplate.getForObject("http://spring-cloud-user/user/" + id, User.class);//直接写服务提供者的spring.application.name,这样方便于动态IP
	  }
	  
	  
	  //两个服务的情况下:一个调用随机的,一个用ribbon调用
	  @GetMapping("/test")
	  public String test() {
	    ServiceInstance serviceInstance = this.loadBalancerClient.choose("spring-cloud-user");
	    System.out.println("test1" + ":" + serviceInstance.getServiceId() + ":" + serviceInstance.getHost() + ":" + serviceInstance.getPort());
	    ServiceInstance serviceInstance2 = this.loadBalancerClient.choose("spring-cloud-user_two");
	    System.out.println("test2" + ":" + serviceInstance2.getServiceId() + ":" + serviceInstance2.getHost() + ":" + serviceInstance2.getPort());
	    return "test";
	  }
}

User类

package com.example.demo.entity;

import java.math.BigDecimal;

public class User {
  private Long id;

  private String username;

  private String name;

  private Short age;

  private BigDecimal balance;

  public Long getId() {
    return this.id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getUsername() {
    return this.username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getName() {
    return this.name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Short getAge() {
    return this.age;
  }

  public void setAge(Short age) {
    this.age = age;
  }

  public BigDecimal getBalance() {
    return this.balance;
  }

  public void setBalance(BigDecimal balance) {
    this.balance = balance;
  }

}

ExcludeFromComponentScan

package com.example.demo;

/**
 * 此接口是为了自定义的ribbon时,配置类在启动类扫描到的包下,需要此注解
 * @author arvin pan
 *
 */
/*public @interface ExcludeFromComponentScan {

}
*/

SpringCloudOrderApplication

package com.example.demo;

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.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

import com.example.config.AutoConfiguration;

/**
 * 通过自定义配置Ribbon
 *
 */

@SpringBootApplication//此注解会扫描本类同级和子级所在的包
@EnableEurekaClient
//此注解表示是一个Ribbon客户端
@RibbonClient(name = "spring-cloud-user", configuration = AutoConfiguration.class)//name只能是在eureka服务注册过的,这里用用户服务

//配置类在启动类扫描到的包下,需要此注解
//@ComponentScan(excludeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION, value = ExcludeFromComponentScan.class) })
public class SpringCloudOrderApplication {

  @Bean	//必须new 一个RestTemplate并放入spring容器当中,否则启动时报错
  @LoadBalanced //此注解整合了Ribbon,使客户端负载均衡
  public RestTemplate restTemplate() {
    return new RestTemplate();
  }

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


application.yml配置

spring:
  application:
    name: spring-cloud-order-ribbon_two   #微服务的名称
server:
  port: 7903  #微服务端口号
eureka:
  client:
    healthcheck:
      enabled: true   # 开启健康检查
    serviceUrl:
      defaultZone: http://user:123456@localhost:8761/eureka   #服务eureka的URL地址
  instance:
    prefer-ip-address: true


pom.xml配置

<?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.example.demo</groupId>
	<artifactId>spring-cloud-order-ribbon_two</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<name>spring-cloud-order-ribbon_two</name>
	<description>spring-cloud-order-ribbon_two</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.1.RELEASE</version>
	</parent>

	<properties>
		<!-- 文件拷贝时的编码 -->  
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		  <!-- 编译时的编码 -->  
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>  
        <!-- jdk版本 -->  
		<java.version>1.8</java.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</artifactId>
		</dependency>
		<!-- 这个库让我们可以访问应用的很多信息,包括:/env、/info、/metrics、/health等 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<!-- 用于热部署 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>		
	</dependencies>
	<dependencyManagement>
		<dependencies>
		<!-- 版本依赖管理,故之后添加依赖无需指定version -->
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>Camden.SR2</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
		<!-- 用以为integration-test提供支持。 -->
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值