从b站学习springcloud,现在进行总结,该总结除去了视频中出现的小错误,对有些易错的地方进行了提醒
b站链接:https://www.bilibili.com/video/av55304977
资料链接:
https://pan.baidu.com/s/1o0Aju3IydKA15Vo1pP4z5w
提取码: 21ru
上一节链接:https://blog.csdn.net/qq_40893824/article/details/103332091
下一节链接:https://blog.csdn.net/qq_40893824/article/details/103336449
下面的内容总结:子工程→pom→application→实体类Student→handler→启动类
实现细节:
1.创建module模块,命名为ribbon
2.该模块的pom文件,添加代码:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
</dependencies>
3.在resource下创application.yml,添加代码:
server:
port: 8040
spring:
application:
name: ribbon
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
#确认注册
4.在java中创包com.southwind,在southwind中创启动类RibbonApplication.java,填入代码:@LoadBalanced 别漏了!
package com.southwind;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class RibbonApplication {
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class,args);
}
@Bean
@LoadBalanced//负载均衡
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
5.在southwind中创包entity,将Student复制至该包内
6.在southwind中创包controller,创RibbonHandler.java,添加代码:
package com.southwind.controller;
import com.southwind.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Collection;
@RestController
@RequestMapping("/ribbon")
public class RibbonHandler {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/findAll")
public Collection<Student> findAll(){
return restTemplate.getForObject("http://provider/student/findAll",Collection.class);
}
@GetMapping("/index")
public String index(){
return restTemplate.getForObject("http://provider/student/index",String.class);
}
}
7.检查是否调通
a.进入http://localhost:8761
b.进入http://localhost:8040/ribbon/index
端口是8010,f5刷新网页:
这样端口一直在8010和8011之间转换,就实现了负载均衡的功能了。
这里我没有写增删查改的代码,因为加上去很简单,把之前的增删查改的代码复制过来就可以了。
zuul和ribbon都有负载均衡功能,作为springcloud小白,我目前认为zuul的操作要比ribbon要简单。
上一节链接:https://blog.csdn.net/qq_40893824/article/details/103332091
下一节链接:https://blog.csdn.net/qq_40893824/article/details/103336449