Springcloud相关组件小练习
每天多学一点点~
话不多说,这就开始吧…进击的爆裂无球~
文章目录
1.前文
坑爹的国网项目终于结束了~~~之前看过一些Springcloud的相关书籍,也写过一个小demo,因很长时间没用,有点遗忘,趁着这次有空,将之前谢的demo整理一下,包含了常用的各种组件,以及各种配置文件,若有幸看到,愿对您有所帮助~
2.准备工作
本文默认读者朋友们看过sprigclou的各种组件,并对其应用有所了解!
本次demo用的是Springcloud的Finchley.SR2版
名称 | 介绍 | 说明 | 端口 |
---|---|---|---|
config-server | 远程配置管理服务 | spring cloud config配置中心,演示基本的config功能 | 2001 |
erureka-server | 微服务注册中心 | 基于REST的定位服务,以实现云端中间层服务发现和故障转移 | 1001 |
mall-portal | 基于REST的定位服务,以实现云端中间层服务发现和故障转移 | feign+ribbon+hystrix+zuul 等组件基本的使用和配置 | 9001 |
service-member | mall会员微服务 | SpringBoot+MybatisPlus框架的业务模块微服务,可随意扩展重建, 附带feign+config+bus等组件的演示,整合Redis+RabbitMQ中间件的基本使用 | 8001 |
service-order | mall订单微服务 | pringBoot+MybatisPlus框架的业务模块微服务,可随意扩展重建,附带feign+config+bus等组件的演示,整合Redis+RabbitMQ中间件的基本使用 | 8002 |
service-product | mall商品微服务 | SpringBoot+MybatisPlus框架的业务模块微服务,可随意扩展重建,附带feign+config+bus等组件的演示,整合Redis+RabbitMQ中间件的基本使用 | 8003 |
zuul-fileupload | zuul文件上传 | 专门测试zuul的大小文件上传 | 8090 |
3.erureka-server注册中心
这个没什么好讲的,注册中心,列出配置
server:
port: 1001
# eureka
eureka:
instance:
hostname: localhost
prefer-ip-address: true # 以IP地址注册到服务中心,相互注册使用IP地址
server:
# 是否开启自我保护模式,默认为true。 默认情况下,如果Eureka Server在一定时间内没有接收到某个微服务实例的心跳,Eureka Server
# 将会注销该实例(默认90秒)。但是当网络分区故障发生时,微服务与Eureka Server之间无法正常通信,以上行为可能变得非常危险了——
# 因为微服务本身其实是健康的,此时本不应该注销这个微服务。
enable-self-preservation: false
# eureka server清理无效节点的时间间隔,默认60000毫秒,即60秒
eviction-interval-timer-in-ms: 30000
client:
register-with-eureka: false # 声明 不将自己 注册到 eureka 服务器 默认为true
fetch-registry: false # 声明 是否到eureka服务器 抓取信息 默认true
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ # eurkeka地址
# spring
spring:
application:
name: erureka-server # 微服务名称
4.config-server配置中心
server:
port: 2001
# eureka
eureka:
instance:
#表示eureka server至上一次收到client的心跳之后,等待下一次心跳的超时时间,在这个时间内若没收到下一次心跳,则将移除该instance。
lease-expiration-duration-in-seconds: 30
#表示eureka client发送心跳给server端的频率。如果在leaseExpirationDurationInSeconds后,server端没有收到client的心跳,则将摘除该instance。
#除此之外,如果该instance实现了HealthCheckCallback,并决定让自己unavailable的话,则该instance也不会接收到流量。
lease-renewal-interval-in-seconds: 10
# 在eureka页面显示 ip和端口号 加这个原因:本机启动这个项目,其他项目在虚拟机启动,没有ip虚拟机连不上这里的服务最好每个都加上这个
# 1.x 版本是 ipAddress 2.x版本是 ip-address
preferIpAddress: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
client:
service-url:
defaultZone: http://localhost:1001/eureka/
# actuator 健康自检
management:
security:
enabled: false
endpoints:
web:
exposure:
include: "bus-refresh" # bus总线,刷新所有集群 的 配置
# spring
spring:
application:
name: config-server # 微服务名称
# config 配置
cloud:
config:
server:
git:
#uri: https://github.com/aaronrao/mall-config.git
uri: https://gitee.com/zjq123456/mall-config.git # 码云仓库地址
# rabbitmq
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
博主之前在码云上放了一些配置文件
dev , test ,prd 分别模拟了开发,测试,生产 三个环境,member,order,product分别模拟了不同的微服务的配置,在后续章节后后贴出配置代码,如何读取到各个服务放在git放的配置!
开启eureka和config服务,调用端口http://localhost:2001/service-member-dev.yml
总线的bus刷新配置文件
调用接口 http://localhost:2001/actuator/bus-refresh
这里大体解释一下:
当你在其他服务,通过config配置中心获取git上的配置文件内容时,如果你不刷新总线,就算你i修改了git上的内容,调用接口还是一样的~后文会将
5.mall-portal商城入口服务
feign+ribbon+hystrix+zuul 等组件基本的使用和配置
- yml配置
server:
port: 9001
# eureka
eureka:
instance:
lease-expiration-duration-in-seconds: 30
lease-renewal-interval-in-seconds: 10
client:
service-url:
defaultZone: http://localhost:1001/eureka/
# feign
feign:
hystrix:
enabled: true # 打开feign 的 hystrix开关
client:
config:
default:
connectTimeout: 10000
readTimeout: 5000
# hystrix 容错框架
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 5000 #超时时间 超过5s机会容错
# ribbon 各个服务对应的ribbon策略
# BestAvailableRule 忽略哪些短路的服务器,并选择并发数较低的服务器
service-product:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.BestAvailableRule
service-member:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.BestAvailableRule
service-order:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.BestAvailableRule
#使用Zuul上传文件
#1、对于小文件(1M以内)上传,无须任何处理,即可正常上传。
#2、对于大文件(10M以上)上传,需要为上传路径添加/zuul前缀。
#注意:这里的上传路径添加/zuul前缀无须配置
# 若 zuul 配置了负载均衡 则需要配置 hystrix的超时时间 用 zuul 传大文件的时候要设置
#hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000
ribbon:
ConnectTimeout: 3000
ReadTimeout: 60000
# zuul 网关映射
zuul:
ignored-services: '*' # 表示关闭所有通过微服务名称来映射访问
routes: # service_id : path 映射 格式
service-product: /apigateway/product/**
service-member: /apigateway/member/**
service-order: /apigateway/order/**
ms-zuul-fileupload: /zuul-fileupload/** # zuul的文件上传 路径 http://localhost:9001/zuul/zuul-fileupload/upload
# ms-zuul-fileupload 是微服务实例,即通过zuul网关访问上传的微服务 要在前面自动加上 /zuul/zuul-fileupload/**
ignored-patterns: /service-*/** # 保护敏感路径 不给/service-*/** 的方式路由
sensitive-headers: # #过滤敏感头信息,若不设置,cookie setcookie 和 authrotion三个同步信息是不能传递的 默认是空的
# actuator 服务监控
#在 application.properties 文件中配置actuator的相关配置,其中info开头的属性,就是访问info端点中显示的相关内容,
#值得注意的是Spring Boot2.x中,默认只开放了info、health两个端点,剩余的需要自己通过配置management.endpoints.web.exposure.include属性来加载
#(有include自然就有exclude,不做详细概述了)。如果想单独操作某个端点可以使用management.endpoint.端点.enabled属性进行启用或禁用
management:
endpoints:
web:
exposure:
include: "*"
# spring
spring:
application:
name: mall-portal
# servlet:
# multipart: # spring设置文件上传的
# max-file-size: 4000MB # 设置文件上传的大小
# max-request-size: 4000MB
- feign调用其他微服务接口
@FeignClient(name = "service-member", fallback = MemberClientFallback.class)
public interface MemberClient {
@GetMapping("/api/user")
String findByName(@RequestParam(value = "username") String username);
}
- hystrix容错框架 控制层容错
@RestController
public class CreateOrderCtrl {
@Autowired
private CreateOrderService createOrderService;
/**
* 进行了容错 是基于 controller的容错
* @param username
* @param productSn
* @param orderSn
* @return
*/
@HystrixCommand(fallbackMethod = "findThingsFail")
@RequestMapping(value = "/api/find/data", method = RequestMethod.GET)
public JSONObject findThings(String username, String productSn, String orderSn) {
//int i = 1/0; // 报错 ,让其进入 容错方法
return createOrderService.findThings(username, productSn, orderSn);
}
private JSONObject findThingsFail(String username, String productSn, String orderSn) {
System.out.println("controller中的降级方法");
JSONObject obj = new JSONObject();
obj.put("code", -1);
obj.put("msg", "抢购人数太多,您被挤出来了,请稍等重试!");
return obj;
}
}
- hystrix容错框架 feign接口容错
@Component
public class MemberClientFallback implements MemberClient {
@Override
public String findByName(String username) {
System.out.println("MemberClientFallback中的降级方法");
JSONObject obj = new JSONObject();
obj.put("id", 9999L);
obj.put("username", "admin");
obj.put("password", "admin");
return obj.toJSONString();
}
}
- zuul网关映射 调用接口
上文yml中配置了映射,通过90001(商场入口服务)调用member服务的接口
zuul:
ignored-services: '*' # 表示关闭所有通过微服务名称来映射访问
routes: # service_id : path 映射 格式
service-product: /apigateway/product/**
调用接口 http://localhost:9001/apigateway/member/api/user?username=baicai
- zuul网关映射 上传文件
yml配置
server.port=8090
spring.application.name=ms-zuul-fileupload
eureka.client.service-url.defaultZone=http://localhost:1001/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=ms-zuul-fileupload-8001
#设置文件上传的大小
spring.servlet.multipart.max-file-size=4000MB
spring.servlet.multipart.max-request-size=4000MB
代码
@Slf4j
@RestController
@RequestMapping("/file")
public class FileUploadController {
@Autowired
private Environment env;
@RequestMapping("/upload")
public Object upload(@RequestParam("file") MultipartFile file) throws IOException {
log.info("上传的文件名称:{}", file.getOriginalFilename());
log.info("文件上传的大小:{}", file.getSize());
String fileName = file.getOriginalFilename();
//文件后缀名
String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
//根据当前时间来创建文件名
String time = Long.toString(System.currentTimeMillis());
StringBuilder sb = new StringBuilder();
sb.append(System.getProperty("user.dir"))
.append(File.separator)
.append("upload")
.append(File.separator)
.append(time)
.append(".")
.append(prefix);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("/upload")
.append("/")
.append("upload")
.append("/")
.append(time)
.append(".")
.append(prefix);
File tempFile = new File(sb.toString());
try {
File targetFile = new File(tempFile.toString());
if (targetFile.exists()) {
return "文件已存在";
}
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
file.transferTo(targetFile);
return "true";
} catch (Exception e) {
e.printStackTrace();
return "false";
}
}
}
调用接口 http://localhost:9001/zuul/zuul-fileupload/file/upload
6.service-order服务
这个服务多了一个bootstrap.yml 配置如下
spring:
application:
name: service-order
# config
cloud:
config:
uri: http://localhost:2001 #微服务 配置中心 地址
profile: dev # 读取 s以服务名 service-order+ dev 的配置文件
label: master #对应git的分支。如果配置中心使用的是本地存储,则该参数无用
discovery:
service-id: config-server # 指定配置中心的service-id,便于扩展为高可用配置集群。
application.yml的配置和protal配置差不多,只是将zuul的写在了bootstrap.yml中
- 读取git上的配置文件
@RefreshScope
@RestController
public class ConfigCtrl {
@Value("${server.profile}")
private String profile;
@GetMapping("/profile")
public String profile() {
return this.profile;
}
}
调用接口 :http://localhost:8002/profile (前提是启动config配置中心)
这里为何是 @Value("${server.profile}") 因为博主在配置文件中写的是这个
若修改了git上配置,请刷新总线bus,再次调用才是最新的值
7.其他服务
剩下的service-member和service-product和service-oordr差不多,这里就不多赘述了
8.总结
博主差不读多把知道的springcloud的各种组件全部包含在内了,在往深处博主也没怎么研究过~若您有幸看到,文中有不对之处,欢迎一起学习探讨!
代码连接
对了,若您下载了,记得给个星,谢谢~
9.结语
世上无难事,只怕有心人,每天积累一点点,fighting!!!