微服务
流量重放
灰度发布
获取当前机器cpu核数
java
Runtime.getRuntime().availableProcessors();估算线程池大小
vim
Nthreads = Ncpu x Ucpu x (1 + W/C),其中
Ncpu = CPU核心数
Ucpu = CPU使用率,0~1
W/C = 等待时间与计算时间的比率时间轮
技巧篇:延迟任务处理神器之时间轮 HashedWheelTimer
- hutool使用
java
public static void main(String[] args) {
SystemTimer timer = new SystemTimer();
timer.setDelayQueueTimeout(1000);
timer.start();
timer.addTask(new TimerTask(() -> {
System.out.println(1);
System.out.println("任务已经完成");
}, 1000));
timer.stop();
System.out.println("线程池已经关闭");
}布隆过滤器(英语:Bloom Filter)
java
// 初始化
BitMapBloomFilter filter = new BitMapBloomFilter(10);
filter.add("123");
filter.add("abc");
filter.add("ddd");
// 查找
filter.contains("abc")jvm
硬核 JVM 压缩指针详解|得物技术亚毫秒GC暂停到底有多香?JDK17+ZGC初体验|得物技术
消息总线
- spring cloud bus
xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-kafka</artifactId>
</dependency>java
# 项目A 发送BusEvent,BusEvent为项目A、B共用
@Data
public class BusEvent extends RemoteApplicationEvent {
private User user;
public BusEvent(User user) {
this.user = user;
}
public BusEvent() {
}
public BusEvent(Object source, User user, String originService, Destination destination) {
super(source, originService, destination);
this.user = user;
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
BusProperties busProperties;
@Resource
PathDestinationFactory pathDestinationFactory;
@GetMapping("/push/bus")
@IgnoreUserToken
public void bus(@RequestParam String userId) {
User user = new User();
user.setUserId(userId);
user.setUserName(userId);
// destination为指定服务消费事件,可以为null,表示所有服务均可消费
SpringUtil.publishEvent(new BusEvent(this, user, busProperties.getId(), pathDestinationFactory.getDestination("example-consumer:**")));
}
}
# 项目B进行事件消费
@Component
@Slf4j
public class EventConsumer implements ApplicationListener<BusEvent> {
@Override
public void onApplicationEvent(BusEvent event) {
log.info("event:{}", event);
}
}yml
spring:
cloud:
bus:
id: ${spring.application.name}
destination: test-my-cloud-bus
stream:
bindings:
springCloudBusInput:
group: ${spring.cloud.bus.id}
springCloudBusOutput:
group: ${spring.cloud.bus.id}java
# bus事件消费源码 org.springframework.cloud.bus.BusConsumer
public class BusConsumer implements Consumer<RemoteApplicationEvent> {
private final Log log = LogFactory.getLog(getClass());
private final ApplicationEventPublisher publisher;
private final ServiceMatcher serviceMatcher;
private final ObjectProvider<BusBridge> busBridge;
private final BusProperties properties;
private final Destination.Factory destinationFactory;
public BusConsumer(ApplicationEventPublisher publisher, ServiceMatcher serviceMatcher,
ObjectProvider<BusBridge> busBridge, BusProperties properties, Destination.Factory destinationFactory) {
this.publisher = publisher;
this.serviceMatcher = serviceMatcher;
this.busBridge = busBridge;
this.properties = properties;
this.destinationFactory = destinationFactory;
}
@Override
public void accept(RemoteApplicationEvent event) {
if (event instanceof AckRemoteApplicationEvent) {
if (this.properties.getTrace().isEnabled() && !this.serviceMatcher.isFromSelf(event)
&& this.publisher != null) {
this.publisher.publishEvent(event);
}
// If it's an ACK we are finished processing at this point
return;
}
if (log.isDebugEnabled()) {
log.debug("Received remote event from bus: " + event);
}
// 注意此处判断,满足该条件this.serviceMatcher.isForSelf(event),发送spring本地事件后,才能被ApplicationListener捕获
if (this.serviceMatcher.isForSelf(event) && this.publisher != null) {
if (!this.serviceMatcher.isFromSelf(event)) {
this.publisher.publishEvent(event);
}
if (this.properties.getAck().isEnabled()) {
AckRemoteApplicationEvent ack = new AckRemoteApplicationEvent(this, this.serviceMatcher.getBusId(),
destinationFactory.getDestination(this.properties.getAck().getDestinationService()),
event.getDestinationService(), event.getId(), event.getClass());
this.busBridge.ifAvailable(bridge -> bridge.send(ack));
this.publisher.publishEvent(ack);
}
}
if (this.properties.getTrace().isEnabled() && this.publisher != null) {
// We are set to register sent events so publish it for local consumption,
// irrespective of the origin
this.publisher.publishEvent(new SentApplicationEvent(this, event.getOriginService(),
event.getDestinationService(), event.getId(), event.getClass()));
}
}
}熔断器
- sentinel
bash
docker run --name sentinel -d -p 8858:8858 -d bladex/sentinel-dashboard:latest- resilience4j
注册中心/配置中心
- nacos
bash
docker run -d -it --restart=always -e RNACOS_ENABLE_NO_AUTH_CONSOLE=true --name nacos -p 8848:8848 -p 9848:9848 -p 10848:10848 qingpan/rnacos:stable
docker run --name nacos-standalone -e MODE=standalone -v /home/ubuntu/docker/nacos/application.properties:/home/nacos/conf/application.properties -p 8848:8848 -p 9848:9848 -d nacos/nacos-server:latestproperties
#application.properties
spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://172.17.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=root
db.password=123456springboot 拓展点
掌握这些 Spring Boot 启动扩展点,已经超过 90% 的人了!
分布式共识算法raft实现sofajraft
https://github.com/sofastack/sofa-jraft
https://www.sofastack.tech/blog/sofa-channel-8-retrospect/
embedded zookeeper
todo
tomcat+TransmittableThreadLocal
yml
#验证设置tomcat线程数
server:
tomcat:
max-threads: 1
min-spare-threads: 1java
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.apache.coyote.AbstractProtocol;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.ttl.threadpool.TtlExecutors;
import cn.hutool.core.thread.ThreadUtil;
@Configuration
public class TomcatConfig {
@Bean
public TomcatServletWebServerFactory tomcatFactory(ServerProperties serverProperties) {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addConnectorCustomizers(connector -> {
// 设置自定义的线程池
AbstractProtocol protocol = (AbstractProtocol)connector.getProtocolHandler();
protocol.setExecutor(createThreadPool(serverProperties));
});
return factory;
}
private Executor createThreadPool(ServerProperties serverProperties) {
ServerProperties.Tomcat tomcat = serverProperties.getTomcat();
ThreadPoolExecutor executor = new ThreadPoolExecutor(tomcat.getMinSpareThreads(), tomcat.getMaxThreads(), 60L,
TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
// 禁用inheritable
TtlExecutors.getDisableInheritableThreadFactory(ThreadUtil.createThreadFactory("my-thread-pool-")),
new ThreadPoolExecutor.DiscardPolicy());
return TtlExecutors.getTtlExecutor(executor);
}
}数据库连接泄露 todo
nio编程库
netty
vert.x
响应式编程
背压(Back-Pressure)
https://juejin.cn/post/7138241196744736799
什么时候需要响应式编程
线程池里无可用线程,新请求进入缓存队列中等待,频繁出现这种情况就需要响应式编程,但是如果线程池未满不需要响应式编程
比如spring cloud zuul 与 spring cloud gateway
https://spring.io/blog/2018/06/20/the-road-to-reactive-spring-cloud/ 对应的译文 https://juejin.cn/post/6844903637097906189
改造成本
基本上是整个链路的改造,参考<<彩虹桥架构演进之路-性能篇 >>,主要看“改造后的架构”这一节
webflux性能测试
【Spring MVC 与 Spring Webflux 性能测试】(https://cloud.tencent.com/developer/article/2328281)
几种数据库驱动beachmark
https://github.com/herouu/beachmark-hikari-jdbc-and-vertx
slims docker image for java
https://www.baeldung.com/spring-docker-liberica
Ways to accelerate JVM startup and warmup (加速JVM启动和预热的方法)
- Application Class Data Sharing (AppCDS)
- Ahead-of-time compilation (Native Image)
- CRaC
