从springboot到springcloud第三篇----springcloud ribbon

上一章搭建完成了eureka服务中心与客户端   并且调用客户端成功

但当用户访问量过多的时候,服务压力会过大,会有出现服务宕机的情况。为保证服务的健壮性,服务大多以集群方式比较好。

 

这一章开始使用ribbon来实现服务调用的负载均衡

 

一、创建ribbon-client项目

二、修改配置文件

spring.application.name=ribbon-client

# 应用服务 WEB 访问端口
server.port=8700

#服务中心地址
eureka.client.serviceUrl.defaultZone=http:localhost:8761/eureka/

三、在启动类上添加注解 @EnableEurekaClient

package com.example.ribbonclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class RibbonClientApplication {

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

}

四、添加配置类

package com.example.ribbonclient.config;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@SpringBootConfiguration
@Component
public class RibbonConfiguration {

    @Bean
    //开启客户端负载均衡
    @LoadBalanced
    RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

五、添加调用方法

package com.example.ribbonclient;

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

@RestController
public class RibbonController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/index")
    public String index(){
        return restTemplate.getForObject("http://eureka-client/index",String.class);
    }
}

六、为显示负载均衡测试效果,再启动一个eureka-client服务

6.1 修改eureka-client配置的端口号 改为

server.port=8763

6.2 修改serviceimpl代码

package com.example.eurekaclient.service.impl;

import com.example.eurekaclient.service.IndexService;
import org.springframework.stereotype.Service;

@Service
public class IndexServiceImpl implements IndexService {

    @Override
    public String getMesasge() {
        return "hello springcloud 8763";
    }
}

6.3 开启idea多服务启动

六、刷新eureka服务监控中心并测试

 

页面多次刷新 测试负载均衡效果

 

 

源码地址: https://github.com/houfanGitHub/springcloud.git

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值