Spring Cloud Ribbon 使用示例--RestTemplate

本文详细介绍了如何在SpringBoot 1.x版本中使用RestTemplate与Eureka服务注册中心配合,实现生产者与消费者之间的服务调用,包括producer-server和consumer-server的配置及Maven依赖。展示了在不同服务间通过Ribbon负载均衡的原理和配置。

版本说明

在Spring Boot 1.X版本中,常用RestTemplate接口实现通讯,而在Spring Boot 2.X版本中,WebFlux提供了异步非阻塞通讯方式,是一种更好的通讯解决方案。

使用RestTemplate

在本示例中,实现了一个Eureka服务注册中心eureka-server,两个生产者服务provider-server,一个消费者服务consumer-server。生产者与消费者均注册到Eureka服务上。消费者将通过Eureka服务获取生产者服务清单,并将通过RestTemplate接口访问生产者服务。在通讯过程中,将使用Ribbon实现负载均衡。

服务注册中心eureka-server

创建一个Spring Boot 工程,命名为eureka-server,并在pom.xml中引入必要的依赖内容,代码如下:

maven依赖

<!-- Spring Boot Parent -->
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>1.3.7.RELEASE</version>
	<relativePath/>
</parent>

<dependencies>
	<!-- Spring Cloud Eureka -->
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-eureka-server</artifactId>
	</dependency>
</dependencies>

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

代码实现

@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
	public static void main(String[] args) {
		new SpringApplicationBuilder(EurekaApplication.class).web(true).run(args);
	}
}

配置文件

该项目只有一个配置文件,即application.yml

server:
	port: 1111

eureka:
	instance:
		hostname: localhost
	client:
		register-with-eureka: false
		fetch-registry: false
		service-url:
			default-zone: http://${eureka.instance.hostname}:${server:port}/eureka/

生产者服务provider-server

Maven依赖

<!-- Spring Boot Parent -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.7.RELEASE</version>
    <relativePath/>
</parent>

<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>
</dependencies>

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

代码实现

Restful服务接口实现如下:

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    private DiscoveryClient client;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String index() {
        ServiceInstance instance = client.getLocalServiceInstance();
        logger.info("/hello, host:" + instance.getHost() + ", service_id :" + instance.getServiceId());
        return "Hello World!";
    }
}

应用主类代码

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableDiscoveryClient
@SpringBootApplication
public class ProviderApplication {

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

配置文件

application.yml配置如下,运行时通过--spring.profiles.active参数指定使用的profile。示例中启动两个provider-server服务,使其构成集群。

spring:
  application:
    name: provider-server

eureka:
  client:
    service-url:
      defaultZone: http://localhost:1111/eureka/

---
spring:
  profiles: provider1
server:
  port: 8081

---
spring:
  profiles: provider2
server:
  port: 8082

消费者服务consumer-server

Maven依赖

<!-- Spring Boot Parent -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.7.RELEASE</version>
        <relativePath/>
    </parent>

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

    <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>

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

代码实现

服务接口实现如下:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = "/ribbon-consumer", method = RequestMethod.GET)
    public String helloConsumer() {
        return restTemplate.getForEntity("http://provider-server/hello", String.class).getBody();
    }
}

应用主类实现如下:

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;

@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApplication {

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

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

配置文件

spring:
  application:
    name: consumer-server

server:
  port: 9000

eureka:
  client:
    service-url:
      defaultZone: http://localhost:1111/eureka/

本文代码改自《Spring Cloud 微服务实战》

Spring Cloud Starter Feign Ribbon Bootstrap AngularJS 是一个基于 Spring Cloud微服务架构项目,它整合了 Feign、Ribbon 和 AngularJS。以下是该项目的一些主要特点和组成部分: 1. **Feign**: Feign 是一个声明式的 Web 服务客户端,使得调用 HTTP 接口变得简单。通过定义一个接口并使用注解来描述请求,Feign 会自动生成代码来实现这些请求。 2. **Ribbon**: Ribbon 是 Netflix 发布的负载均衡器,它可以与 Feign 结合使用,实现对多个服务实例的负载均衡。 3. **Bootstrap**: 在 Spring Cloud 中,Bootstrap 通常用于加载配置信息。在这个项目中,Bootstrap 可能用于加载一些全局配置或初始化一些资源。 4. **AngularJS**: AngularJS 是一个前端 JavaScript 框架,用于构建动态的单页面应用(SPA)。在这个项目中,AngularJS 可能用于开发前端界面,与后端的 Spring Cloud 服务进行交互。 5. **Spring Cloud Starter**: Spring Cloud Starter 是一组自动化配置的集合,简化了 Spring Cloud 应用程序的开发。在这个项目中,Spring Cloud Starter 提供了 Feign 和 Ribbon 的自动配置。 6. **项目结构**: 这个项目的结构可能包括以下几个部分: - `src/main/java`: 存放 Java 源代码文件。 - `src/main/resources`: 存放配置文件,如 application.yml 或 application.properties。 - `src/main/webapp`: 存放静态资源文件,如 HTML、CSS 和 JavaScript 文件。 - `src/test/java`: 存放单元测试代码。 - `pom.xml`: Maven 项目的配置文件,用于管理项目依赖和构建过程。 7. **依赖管理**: 在 pom.xml 文件中,可能会包含以下依赖: - Spring Boot Starter Web - Spring Cloud Starter OpenFeign - Spring Cloud Starter Netflix Ribbon - AngularJS (如果使用 Maven 进行前端依赖管理) 8. **示例代码**: 以下是一个简化的示例代码,展示了如何使用 Feign 和 Ribbon 进行服务调用: ```java @FeignClient(name = "service-name", configuration = FeignConfig.class) public interface ServiceClient { @RequestMapping(value = "/api/resource", method = RequestMethod.GET) String getResource(); } @Configuration public class FeignConfig { @Bean public IRule ribbonRule() { return new RoundRobinRule(); // 使用轮询策略进行负载均衡 } } @RestController public class MyController { @Autowired private ServiceClient serviceClient; @GetMapping("/my-endpoint") public String myEndpoint() { return serviceClient.getResource(); } } ``` 9. **注意事项**: 在使用 Spring Cloud Starter Feign Ribbon Bootstrap AngularJS 时,需要注意以下几点: - 确保所有依赖的版本兼容。 - 正确配置 Feign 和 Ribbon 的相关属性。 - 如果使用 AngularJS,确保前端代码与后端 API 正确对接。 - 处理可能出现的异常和错误情况。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值