IT学习笔记--Spring Boot/Cloud

Spring Boot:

1.Spring Boot简介:

Spring boot特点:只使用一个核心配置文件,取消了一系列xml配置,甚至连web.xml都没有, 全部使用注解的方式完成WEB层的功能。框架内置Tomcat服务器,运行启动类中的Main函数即可启动。

它最重要的是以下四个核心:

  • 自动配置:针对很多Spring应用程序常见的应用功能, Spring Boot能自动提供相关配置。
  • 起步依赖:告诉Spring Boot需要什么功能,它就能引入需要的库。
  • 命令行界面:这是Spring Boot的可选特性,借此你只需写代码就能完成完整的应用程序,
    无需传统项目构建。
  • Actuator:让你能够深入运行中的Spring Boot应用程序,一探究竟。主要是提供在运行时检视应用程序内部情况的能力。

Spring Boot 具有如下特性:

  • 创建独立的 Spring 应用程序,为开发者提供更快的入门体验 。
  • 尽可能地 自动配置,开箱 即用 。
  • 没有代码生成, 也无须 XML 配置,同时也可以修改默认值来满足特定的需求。
  • 提供了一些大型项目中常见的非功能性特性,如嵌入式服务器、安全、指标、健康检测、外部配置等 。
  • 并不是对 Spring 功能上的增强,而是提供了 一种快速使用 Spring 的方式。

2. 工程搭建

具体可参考这篇博文:Intellij IDEA 搭建Spring Boot项目

生成的项目中,resources文件夹下,static文件夹下存放静态文件,比如css、js、html和图片等 ;templates下存放html文件,controller默认访问该文件夹下的html文件;这个在application.properties配置文件中是可以修改的。

3. @SpringBootApplication开启了Spring的组件扫描和Spring Boot的自动配置功能。实际上, @SpringBootApplication将三个有用的注解组合在了一起:

  • Spring的@Configuration:标明该类使用Spring基于Java的配置。
  • Spring的@ComponentScan:启用组件扫描,这样你写的Web控制器类和其他组件才能被自动发现并注册为Spring应用程序上下文里的Bean。
  • Spring Boot 的 @EnableAutoConfiguration :这个不起眼的小注解也可以称为@Abracadabra①,就是这一行配置开启了Spring Boot自动配置的魔力,让你不用再写成篇的配置了。

4. 使用spring boot+mybatis,使用IntelliJ IDEA开发,记录一些问题的解决方法:

1)在使用@Mapper注解方式代替XXmapper.xml配置文件,使用@Select等注解配置sql语句的情况下,如何配置数据库字段名到JavaBean实体类属性命的自动驼峰命名转换?

使用spring boot后,越来越喜欢用注解方式进行配置,代替xml配置文件方式。mybatis中也可以完全使用注解,避免使用xml方式配置mapper。

(参考  springboot(六):如何优雅的使用mybatis  http://www.ityouknow.com/springboot/2016/11/06/springboot(%E5%85%AD)-%E5%A6%82%E4%BD%95%E4%BC%98%E9%9B%85%E7%9A%84%E4%BD%BF%E7%94%A8mybatis.html

设置自动驼峰命名转换,在xml中可以直接配置mapUnderscoreToCamelCase属性。但是使用注解方式时,经过一番查找资料才找到比较好的设置方法。如下:

在spring boot的配置文件application.properties中,加入配置项:

mybatis.configuration.mapUnderscoreToCamelCase=true
 或
mybatis.configuration.map-underscore-to-camel-case=true

设为true表示开启驼峰转换。经过试验,两种配置方法都可以。但如果同时配置,前者mybatis.configuration.mapUnderscoreToCamelCase的优先级更高。

参考:

官方的配置说明 mybatis-spring-boot-autoconfigure – MyBatis Sring-BootStarter | Reference Documentation  http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/#Configuration

SpringBoot之Mybatis - 王念博客  https://my.oschina.net/wangnian/blog/667764

另外查到有通过javaConfig方式,配置org.apache.ibatis.session.SqlSessionFactory的Bean,放入spring的对象池。mapUnderscoreToCamelCase是org.apache.ibatis.session.Configuration的一个属性,实例化Configuration对象并将其mapUnderscoreToCamelCase属性设为true,再使用这个Configuration对象作为SqlSessionFactory的配置即可使mapUnderscoreToCamelCase=true生效。

但是仅仅为了改变一个属性的值,就自己编码生成一个SqlSessionFactory未免太繁琐了些。使用在application.properties中配置的方法更方便。

2)mybatis管理的@Mapper的Dao,在使用@Autowire自动注入时,IDEA有红色报错“could not autowire”,但实际运行时正常,如何去除报错?

按照本人的理解,这个报错是由于Dao接口只添加了mybatis自定义的@Mapper注解,没有添加spring定义的@Component、@Repository等,所以IDEA不认为这是纳入Spring管理的Bean,导致在IDEA找不到autowire的Dao的来源。

查找解决方法,找到了这里的问答:

java - Idea inspects batis mapper bean wrong - Stack Overflow  https://stackoverflow.com/questions/25379348/idea-inspects-batis-mapper-bean-wrong

里面提到安装【MyBatis plugin】插件可以解决,但是我尝试安装这个插件并启用后,仍然有红色报错(插件已经激活,不是license导致的问题),所以猜测这个插件可能是只针对XXmapper.xml配置的方式有效,而对@Mapper注解Dao interface的方式无效(针对后一种情况是否有效,大家尝试了可以反馈下结果)。

所以只好采用一种折中的不算完美的办法,在Dao interface中添加@Mapper的同时,再添加@Repository(或者@Component也可以),如下方代码的第1行:

@Repository
@Mapper
public interface UserDao {

    @Select("SELECT phone FROM user WHERE name = #{name}") //动态传入表名,可以使用 ...FROM ${tableName}... ,但需要解决sql注入风险
    String getPhoneByUserName(@Param("name") String name);
}

5.Spring Boot核心配置文件

它的核心配置文件是application.properties;可以配置默认的tomcat端口号等;

可以进行多环境配置文件:

当resources内包含多个环境的配置文件,如:测试用的配置文件application-test.properties、开发用的配置文件application-dev.properties和上线用的配置文件application-online.properties;在核心配置文件中使用spring.profiles.active=test即可激活测试用的配置文件application-test.properties。有激活的就优先使用激活的配置文件,激活的配置文件没有配置的,就使用当前的配置选项。

6.读取自定义配置

在核心配置文件application.properties中添加自定义配置如下:

#自定义配置
boot.name=您好吗
boot.location=青岛李沧区

有两种方式进行读取:

1)使用@Value注解,如下:

/**
 * 读取自定义配置方式一
 */
@Controller
public class ConfigInfoController {
    @Value("${boot.name}")
    private String name;

    @Value("${boot.location}")
    private String location;

    @RequestMapping("/boot/config")
    public @ResponseBody String config(){
        //方式一测试
        return name + "---" + location;
    }
}

2)使用@ConfigurationProperties,如下:

/**
 * 读取自定义配置方式二
 */
@Component   //使用组件注解
@ConfigurationProperties(prefix="boot")//参数prefix定义配置参数boot.name等的前缀boot
public class ConfigInfo {

    private String name;//直接使用参数配置boot.name的name来绑定
    private String location;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}

访问这两个配置参数变量值,如下:

 @Autowired
 ConfigInfo configInfo;

 @RequestMapping("/boot/config")
 public @ResponseBody String config(){
     //方式二测试
     return configInfo.getName() + "---" + configInfo.getLocation();
 }

7.Spring boot下的Spring mvc

主要注意几个注解的使用和含义:

1)@Controller:与之前的Spring mvc的含义和用法一样

2)@RestController:相当于@Controller与@ResponseBody的组合。使用该注解可以免去@ResponseBody的使用,返回Json或字符串。如下:

@RestController //相当于@Controller+@ResponseBody
public class MvcController {
    @RequestMapping("/boot/rest")
    public Object getUser(){
        User user = new User();
        user.setId(1000);
        user.setName("xudasong");
        return user;
    }
}

3)@GetMapping:相当于@RequestMapping与get方法的组合,即@RequestMapping(value="/boot/hello", method=RequestMethod.GET)

4)同理,@PostMapping、@PutMapping、@DeleteMapping

8.Spring boot下使用jsp

需要注意的一点:即在pom.xml文件,在<build></build>标签内加上:

        <resources>
            <resource>
                <directory>src/main/webapp</directory>
                <targetPath>META-INF/resources</targetPath>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>

否则在Controller种返回jsp页面时会报404错误。

关于jsp页面前缀和后缀的配置,可在核心配置文件application.properties里加上:

spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp

9.Spring boot 与Mybatis整合

开发步骤如下:

 在pom.xml下加上maybatis代码自动生成插件,如下:

10.Spring boot 事务支持

使用事务(即出现异常时支持回滚)非常简单:

1)在入口类中使用注解@EnableTransationManagement开启事务支持;

2)在访问数据库的Service方法上添加注解@Transactional即可。

11.Spring boot 实现RestFull主要是几个注解实现

1)@PathVariable

  • 获取url中的数据;
  • 该注解是实现RestFull最主要的一个注解。
@RequestMapping("/boot/user/{id}/name")
    public Object user(@PathVariable(id) Integer id,@PathVariable(name) String name){
        User user = new User();
        user.setId(id);
        user.setName(name);
        return user;
    }

//访问格式:http://localhost:8080/boot/user/106/xudasong

2)增加 post方法

  • 使用PostMapping;
  • 接收和处理Post的请求

3)删除 delete方法

  • DeleteMapping;
  • 接收delete方式的请求,可以使用GetMapping代替

4)修改 put方法

  • PutMapping
  • 接收put方式的请求,可以使用PostMapping代替

5)查询  get方法

  • GetMapping
  • 接收get方式的请求

11.spring boot集成使用Redis

具体步骤如下:

应用实例:

注意

  • 使用时注意将实体类进行序列化,即实现Serializable.
  • spring boot帮我们注入的RedisTemplate类,泛型里面只能写<String, String>、<Object, Object>

上面的实例在高并发条件下会出现缓存穿透的问题,下面是解决这个问题的修改后的:

测试上面的缓存穿透问题的代码(使用多线程):

其中Executors.newFixedThreadPool(25)表示使用线程池开启25个线程。

Spring Cloud:

1. Spring提供了一系列工具,可以帮助开发人员迅速搭建分布式系统中的公共组件(比如:配置管理,服务发现,断路器,智能路由,微代理,控制总线,一次性令牌,全局锁,主节点选举, 分布式session, 集群状态)。协调分布式环境中各个系统,为各类服务提供模板性配置。使用Spring Cloud, 开发人员可以搭建实现了这些样板的应用,并且在任何分布式环境下都能工作得非常好,小到笔记本电脑, 大到数据中心和云平台。

具体部署实践可看考这篇博文:随笔分类 - Spring Cloud

2. Spring Cloud开发中遇到的坑

(1)服务调用者在进行调用服务提供者的时候参数始终传递不到服务提供者层(我用的是path路径传参数) ,后来发现是在controller层的方法参数前也要添加@PathVariable,只在接口上添加时不行的。

(2)微服务之间调用传参时,使用@RequestBody传JSON数据时,在@PostMapping括号内必须加入consumes=MediaType.APPLICATION_JSON_UTF8_VALUE,如:

@RequestMapping(value="/api/test,consumes="MediaType.APPLICATION_JSON_UTF8_VALUE)
public void login(@RequestBody LoginRequest request){}

其中,consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html; 还有produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回。

(3)当微服务提供方的API的服务有根路径时,调用方在继承提供方接口的同时需要在@FeignClient注解括号内加入path参数,即context_path,如:

@FeignClient(value="提供方服务名",path="提供方根路径")
public interface TestFeignClient extends TestService{}

(4)微服务使用spring自带的RestTemplate进行微信api的URI请求时,内网访问失败,需加入如下配置:

package com.example.springbootdemo.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * 用于内网访问外网的REST请求配置
 */
@Configuration
public class RestTemplateConfig {

    //基于jdk的Spring的RestTemplate
    @Bean
    @Primary
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000); //ms
        factory.setConnectTimeout(5000); //ms
        return factory;
    }

    //基于springcloud的RestTemplate
    @LoadBalanced
    @Bean
    RestTemplate loadBalanced(){
        return new RestTemplate();
    }

}

(5)微服务多服务注册中心,防止以机器名注册,而以IP进行注册的办法,配置文件需加入如下:

eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}

(6)spring-cloud-dependencies的版本与spring-cloud-starter-openfeign和spring-cloud-starter-netflix-eureka-client的版本是有依赖关系的,要不然版本对应不上feign调用的时候会报错。

 解决办法:

spring-cloud-dependencies版本依赖放在<dependencyManagement>中,即:

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

而spring-cloud-starter-openfeign和spring-cloud-starter-netflix-eureka-client两个依赖不要写版本号,maveb会自动根据spring-cloud-dependencies的版本下载相应版本的jar包,同时放在<dependencies>下,即:

<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-openfeign</artifactId>
		</dependency>
<dependencies>

(7)spring-boot升到2.1.6版本时启动会报某个.class类已存在的错误,解决办法是在配置文件加上以下一句:

spring.main.allow-bean-definition-overring=true 即当遇到同名字的时候,是否允许覆盖注册

Spring Cloud Hystrix:

Hystrix被称为熔断器,它是一个用于处理分布式系统的延迟和容错的开源库,在分布式系统里,许多服务之间通过远程调用实现信息交互,调用时不可避免会出现调用失败,比如超时、异常等原因导致调用失败,Hystrix能够保证在一个服务出问题的情况下,不会导致整体服务失败,避免级联故障(服务雪崩),以提高分布式系统的弹性。

基本使用:

服务消费者引入依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

启动类加上@EnableCircuitBreaker 注解:

启动类上加上@EnableCircuitBreaker注解以开启断路器,由于@SpringCloudApplication@EnableHystrix都继承该注解,所以以上三种注解都可以实现开始断路器的功能。

@SpringBootApplication
@EnableFeignClients("cn.bigcoder.springcloud.qa.admin")
@EnableEurekaClient
@EnableCircuitBreaker
public class AdminWebApplication {

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

}

在调用远程服务(消费者)的方法上加入@HystrixCommand注解:

在调用远程服务(消费者)的方法上加入@HystrixCommand注解,并提供一个服务降级后的调用方法。

@RequestMapping("/getArticleById2")
@HystrixCommand(fallbackMethod = "articleFallback")
public ArticleDTO getArticleById2(Integer id) {
    ArticleDTO articleDTO = articleService.getById(id);
    return articleDTO;
}

public ArticleDTO articleFallback(Integer id) {
    return new ArticleDTO();
}

熔断器配置:

Hystrix超时降级:

当调用超时或者抛出异常时会使用降级方法兜底,我们可以修改服务的超时时间(默认是1s):

@RequestMapping("/getArticleById2")
@HystrixCommand(fallbackMethod = "articleFallback",commandProperties = {
        @HystrixProperty(name = "execution.timeout.enabled",value = "true"),
        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
})
public ArticleDTO getArticleById2(Integer id) {
    ArticleDTO articleDTO = articleService.getById(id);
    return articleDTO;
}

需要注意的是:如果hystrix.command.default.execution.timeout.enabledtrue,则会有两个配置方法超时的配置,一个就是ribbon的ReadTimeout,一个就是熔断器hystrixtimeoutInMilliseconds,此时谁的值小谁生效;如果hystrix.command.default.execution.timeout.enabled为false,则熔断器不进行超时熔断,而是根据ribbon的ReadTimeout抛出的异常而熔断,也就是取决于ribbon的ConnectTimeout,配置的是请求服务的超时时间,除非服务找不到,或者网络原因,这个时间才会生效;

ribbon.ReadTimeout=6000
ribbon.ConnectTimeout=3000

可以通过注解修改服务的超时时间,我们还可以有个配置文件设置服务默认的超时时间:

ribbon.ReadTimeout=6000
ribbon.ConnectTimeout=3000
hystrix.command.default.execution.timeout.enabled=true
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000

Hystrix异常处理:

我们在调用服务提供者时,服务提供者可能抛出异常,我们自己也可能抛异常,默认情况下方法抛了异常会自动进行服务降级,交给服务降级中的方法去处理;

当我们自己发生异常后,只需要在服务降级方法中添加一个 Throwable 类型的 :

@RequestMapping("/getArticleById2")
@HystrixCommand(fallbackMethod = "articleFallback", commandProperties = {
        @HystrixProperty(name = "execution.timeout.enabled", value = "true"),
        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
})
public ArticleDTO getArticleById2(Integer id) {
    ArticleDTO articleDTO = articleService.getById(id);
    return articleDTO;
}

public ArticleDTO articleFallback(Integer id, Throwable throwable) {
    ArticleDTO articleDTO = new ArticleDTO();
    articleDTO.setId(id);
    articleDTO.setTitle("服务降级!!!!,error:"+throwable.getMessage());
    return articleDTO;
}

 如果我们需要指定特定异常不降级时,只需要通过ignoreExceptions配置即可:

RequestMapping("/getArticleById2")
@HystrixCommand(fallbackMethod = "articleFallback",
        ignoreExceptions = RuntimeException.class)
public ArticleDTO getArticleById2(Integer id) {
    ArticleDTO articleDTO = articleService.getById(id);
    return articleDTO;
}

Hystrix限流:

hystrix限流就是限制你某个微服务的使用量(可用线程数、缓存任务量)。hystrix通过线程池的方式来管理微服务的调用,它默认是一个线程池(大小10个) 管理你的所有微服务。

Hystrix相关配置: 

Execution相关的属性的配置:

  • hystrix.command.default.execution.isolation.strategy:隔离策略,默认是Thread, 可选Thread|Semaphore(信号量)
  • hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds:执行的超时时间,默认1000ms
  • hystrix.command.default.execution.timeout.enabled:执行是否启用超时,默认启用true
  • hystrix.command.default.execution.isolation.thread.interruptOnTimeout:发生超时是是否中断,默认true
  • hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests 最大并发请求数,默认10,该参数当使用ExecutionIsolationStrategy.SEMAPHORE策略时才有效。如果达到最大并发请求数,请求会被拒绝。理论上选择semaphore size的原则和选择thread size一致,但选用semaphore时每次执行的单元要比较小且执行速度快(ms级别),否则的话应该用thread。semaphore应该占整个容器(tomcat)的线程池的一小部分。 Fallback相关的属性 这些参数可以应用于Hystrix的THREAD和SEMAPHORE策略;
  • hystrix.command.default.fallback.isolation.semaphore.maxConcurrentRequest:如果并发数达到该设置值,请求会被拒绝和抛出异常并且fallback不会被调用。默认10
  • hystrix.command.default.fallback.enabled:当执行失败或者请求被拒绝,是否会尝试调用hystrixCommand.getFallback() 。默认true

Circuit Breaker相关的属性:

  • hystrix.command.default.circuitBreaker.enabled:用来跟踪circuit的健康性,如果未达标则让request短路。默认true

  • hystrix.command.default.circuitBreaker.requestVolumeThreshold:一个rolling window内最小的请求数。如果设为20,那么当一个rolling window的时间内(比如说1个rolling window是10秒)收到19个请求, 即使19个请求都失败,也不会触发circuit break。默认20 hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds 触发短路的时间值,当该值设为5000时,则当触发circuit break后的5000毫秒内都会拒绝request,也就是5000毫秒后才会关闭circuit。 默认5000

  • hystrix.command.default.circuitBreaker.errorThresholdPercentage:错误比率阀值,如果错误率>=该 值,circuit会被打开,并短路所有请求触发fallback。默认50

  • hystrix.command.default.circuitBreaker.forceOpen:强制打开熔断器,如果打开这个开关,那么拒绝所有request,默认false

  • hystrix.command.default.circuitBreaker.forceClosed:强制关闭熔断器,如果这个开关打开,circuit将 一直关闭且忽略circuitBreaker.errorThresholdPercentage

Metrics相关参数:

  • hystrix.command.default.metrics.rollingStats.timeInMilliseconds:设置统计的时间窗口值的,毫秒值,circuit break 的打开会根据1个rolling window的统计来计算。若rolling window被设为10000毫秒,则rolling window会被分成n个buckets,每个bucket包含success,failure,timeout,rejection的次数的统计信息。默认10000
  • hystrix.command.default.metrics.rollingStats.numBuckets:设置一个rolling window被划分的数 量,若numBuckets=10,rolling window=10000,那么一个bucket的时间即1秒。必须符合rolling window % numberBuckets == 0。默认10
  • hystrix.command.default.metrics.rollingPercentile.enabled:执行时是否enable指标的计算和跟踪, 默认true
  • hystrix.command.default.metrics.rollingPercentile.timeInMilliseconds:设置rolling percentile window的时间,默认60000
  • hystrix.command.default.metrics.rollingPercentile.numBuckets:设置rolling percentile window的numberBuckets。逻辑同上。默认6
  • hystrix.command.default.metrics.rollingPercentile.bucketSize:如果bucket size=100,window =10s,若这10s里有500次执行,只有最后100次执行会被统计到bucket里去。增加该值会增加内存开销以及排序 的开销。默认100
  • hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds:记录health 快照(用 来统计成功和错误绿)的间隔,默认500ms

Request Context 相关参数:

  • hystrix.command.default.requestCache.enabled:默认true,需要重载getCacheKey(),返回null时不缓存
  • hystrix.command.default.requestLog.enabled:记录日志到HystrixRequestLog,默认true

Collapser Properties 相关参数:

  • hystrix.collapser.default.maxRequestsInBatch:单次批处理的最大请求数,达到该数量触发批处理,默认 Integer.MAX_VALUE
  • hystrix.collapser.default.timerDelayInMilliseconds:触发批处理的延迟,也可以为创建批处理的时间 +该值,默认10
  • hystrix.collapser.default.requestCache.enabled:是否对HystrixCollapser.execute() and HystrixCollapser.queue()的cache,默认true ThreadPool 相关参数

ThreadPool相关参数:

线程数默认值10适用于大部分情况(有时可以设置得更小),如果需要设置得更大,那有个基本得公式可以 follow: requests per second at peak when healthy × 99th percentile latency in seconds + some breathing room 每秒最大支撑的请求数 (99%平均响应时间 + 缓存值) 比如:每秒能处理1000个请求,99%的请求响应时间是60ms,那么公式是: 1000 (0.060+0.012)基本得原则时保持线程池尽可能小,他主要是为了释放压力,防止资源被阻塞。 当一切都是正常的时候,线程池一般仅会有1到2个线程激活来提供服务:

  • hystrix.threadpool.default.coreSize:并发执行的最大线程数,默认10
  • hystrix.threadpool.default.maxQueueSize:BlockingQueue的最大队列数,当设为-1,会使用SynchronousQueue,值为正时使用LinkedBlcokingQueue。该设置只会在初始化时有效,之后不能修改threadpool的queue size,除非reinitialising thread executor。默认-1。
  • hystrix.threadpool.default.queueSizeRejectionThreshold:即使maxQueueSize没有达到,达到 queueSizeRejectionThreshold该值后,请求也会被拒绝。因为maxQueueSize不能被动态修改,这个参数将允 许我们动态设置该值。if maxQueueSize == ­1,该字段将不起作用
  • hystrix.threadpool.default.keepAliveTimeMinutes:如果corePoolSize和maxPoolSize设成一样(默认 实现)该设置无效。如果通过plugin(https://github.com/Netflix/Hystrix/wiki/Plugins)使用自定义 实现,该设置才有用,默认1.
  • hystrix.threadpool.default.metrics.rollingStats.timeInMilliseconds:线程池统计指标的时间,默 认10000
  • hystrix.threadpool.default.metrics.rollingStats.numBuckets:将rolling window划分为n个 buckets,默认10;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值