先在application.yml文件中添加:比如自定义60秒,注意驼峰命名变量
generalPlatformProperties: #请求第三方超时时间自定义,默认15000ms
httpMaxConnectionTime: 60000
创建对应的类和属性:
@Data
@Component
@ConfigurationProperties(prefix = "general")
public class GeneralPlatformProperties {
//为属性赋值
@Value("${generalPlatformProperties.httpMaxConnectionTime}")
private Integer httpMaxConnectionTime;
}
在代码中使用:我写在业务层,你随意
@Service
public class DemoServiceImpl implements DemoService {
@Autowired
private generalPlatformProperties generalPlatformProperties;
//获取数据。封装起来,方便其他请求使用
public RequestConfig getClientRequestConfig() {
Integer httpMaxConnectionTime = generalPlatformProperties.getHttpMaxConnectionTime();//获取自定义的秒数
if(ObjectUtils.isEmpty(httpMaxConnectionTime) || httpMaxConnectionTime<=15000)httpMaxConnectionTime = 15000;//默认15秒
RequestConfig requestConfig=RequestConfig.custom()
//.setSocketTimeout(httpMaxConnectionTime)//数据交互的时间,我不加(狗头保命)
.setConnectTimeout(httpMaxConnectionTime)//建立连接超时
.setConnectionRequestTimeout(httpMaxConnectionTime)//从连接池获取到连接的超时时间,没有可以不加
.setStaleConnectionCheckEnabled(true).build();
return requestConfig;
}
//业务逻辑中引用getClientRequestConfig()
@Override
public String getDemoData() {
//此处省略一万字...
CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(getClientRequestConfig()).build();
//此处省略一万字...
}
}
不自定义配置的话,yml文件里直接把变量值删掉就可,yml里的变量名不能删。