alice52 / practice Goto Github PK
View Code? Open in Web Editor NEWThis repo is my best practice code.
License: MIT License
This repo is my best practice code.
License: MIT License
-ea -Xmx100m -Xms100m -XX:+HeapDumpOnOutOfMemoryError
-ea -Xmx200m -Xms200m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=. -XX:+PrintGCDateStamps -XX:+PrintGCDetails -Xloggc:gc.log -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=100M
// jdk 自带的: 不是很好用
jhat -port 7401 -J-Xmx4G java_pid85580.hprof
[show retained set]
server.max-http-header-size=10000000
RandomAccess & Deque
Arrays
List
// 或者 spring.jackson.serialization.write_enums_using_index=true
@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer(){
return builder -> builder.featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_INDEX);
}
@JsonCreator
来指定构造方法@JsonProperty
设置构造方法中参数对应的 JSON 属性名read_unknown_enum_values_using_default_value
@JsonEnumDefaultValue UNKNOWN(-1, "未知");
@JsonValue
@JsonValue
字段: 自定义一个 EnumDeserializer, 并注册到 jackson 配置中@Slf4j
@Getter
@AllArgsConstructor
public enum StatusEnumClient {
CREATED(1, "已创建"),
PAID(2, "已支付"),
DELIVERED(3, "已送到"),
FINISHED(4, "已完成"),
@JsonEnumDefaultValue
UNKNOWN(-1, "未知");
@JsonValue private final int status;
private final String desc;
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer() {
return builder -> {
builder.locale(Locale.CHINA);
builder.timeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
builder.simpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
builder.featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_INDEX);
// spring.jackson.deserialization.read_unknown_enum_values_using_default_value=true
builder.featuresToEnable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE);
SimpleModule module = new SimpleModule();
module.addDeserializer(Enum.class, new EnumDeserializer());
builder.modules(module);
};
}
@Bean
public RestTemplate restTemplate(MappingJackson2HttpMessageConverter converter) {
return new RestTemplateBuilder().additionalMessageConverters(converter).build();
}
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
public class EnumDeserializer extends JsonDeserializer<Enum> implements ContextualDeserializer {
private Class<Enum> targetClass;
@Override
public Enum deserialize(JsonParser p, DeserializationContext ctxt) {
// 找枚举中带有@JsonValue注解的字段,这个字段是我们反序列化的基准字段
Optional<Field> valueFieldOpt = Arrays.asList(targetClass.getDeclaredFields()).stream()
.filter(m -> m.isAnnotationPresent(JsonValue.class)).findFirst();
if (valueFieldOpt.isPresent()) {
Field valueField = valueFieldOpt.get();
if (!valueField.isAccessible()) {
valueField.setAccessible(true);
}
// 遍历枚举项,查找字段的值等于反序列化的字符串的那个枚举项
return Arrays.stream(targetClass.getEnumConstants())
.filter(e -> valueField.get(e).toString().equals(p.getValueAsString()))
.findFirst()
.orElseGet(
() -> Arrays.stream(targetClass.getEnumConstants())
.filter(e -> {
// 如果找不到,那么就需要寻找默认枚举值来替代,同样遍历所有枚举项,查找@JsonEnumDefaultValue注解标识的枚举项
return targetClass.getField(e.name()).isAnnotationPresent(JsonEnumDefaultValue.class);
})
.findFirst().orElse(null));
}
return null;
}
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
targetClass = (Class<Enum>) ctxt.getContextualType().getRawClass();
return new EnumDeserializer(targetClass);
}
}
version: '3.0'
services:
actuator-server:
image: registry.cn-shanghai.aliyuncs.com/alice52/practice-actuator-server:20210608.09ec081
restart: 'on-failure:3'
container_name: dev-actuator-server
ports:
- 8010:8010
environment:
TZ: Asia/Shanghai
project-worklow:
image: registry.cn-shanghai.aliyuncs.com/alice52/practice-custom-test:20210608.09ec081
restart: 'on-failure:3'
container_name: dev-project-worklow
volumes:
- /root/project-name/logs:/log
ports:
- 8010:8080
environment:
- TZ=Asia/Shanghai
- spring.profiles.active=cloud
- spring.boot.admin.client.instance.prefer-ip=true
# This is client server public ip
- spring.boot.admin.client.instance.service-base-url=http://xxx:8010
/**
* Notice: if donnot config redis as CacheManager, it will use memory as CacheManager.
*
* @param factory
* @return
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration config =
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ZERO)
.serializeKeysWith(
RedisSerializationContext.SerializationPair.fromSerializer(
stringRedisSerializer))
.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(j2jrs))
.disableCachingNullValues();
return RedisCacheManager.builder(factory).cacheDefaults(config).build();
}
spring:
redis:
host: ENC(7KovIsPRdqwCfirn4hqyvyImWNCj0p/ag5rLhqKqMjiZ9HcC54uBFalQrr9h00lq)
password: ENC(JIczcGuavcI1nX9NbM0YcDyHiQ834QTPhqmczAw+Qr8Nm6wPeq5p5M076HzPSbFF)
port: ENC(AcXQfYO9iFqD0RYGjek03cmHP3k9y7fl9HEy41cg/mr0xoT4ApjXUbtlpKNK8OCp)
database: 13
enable: true
redisson: classpath:redisson-dev.yml
# cache:
# # fix error: Cannot find cache named 'xx' for Builder Or Config Redis as cache management
# type: simple
this jar can be reference by any boot project
version:
3.0.0
2.3.0
and at least 2.2.2
default global Unified exception handler
base exception: based on Assert + Enum
task
diagram
expectation
spring boo version
swagger properties
can enable or disable this feature
200, 401, 400, 500, 404
// version 1: failed api status can be 200 or 400 by configuring
{
"code": 200,
"message": "success",
"data": {
"name": "zack"
}
}
{
"code": 50002,
"message": "User is not exist!",
"data": null
}
{
"code": 40001,
"message": "Not Found!",
"data": null
}
// version 2, outdate, and not implemnt
{
"name": "zack"
}
{
"code": 50002,
"message": "User is not exist!",
}
{
"code": 40001,
"message": "Not Found!",
}
@Transactional
才能生效@Transactional
注解的方法, 事务才能回滚@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMI)
[事件]; 而不是去修改事务的隔离级别propagation = Propagation.REQUIRES_NEW
@Transactional
public void createUserWrong2(UserEntity entity) {
createMainUser(entity);
try{
subUserService.createSubUserWithExceptionWrong(entity);
} catch (Exception ex) {
// 虽然捕获了异常,但是因为没有开启新事务,而当前事务因为异常已经被标记为rollback了,所以最终还是会回滚。
log.error("create sub user error:{}", ex.getMessage());
}
}
private void createMainUser(UserEntity entity) {
userRepository.save(entity);
log.info("createMainUser finish");
}
@Transactional
public void subUserService#createSubUserWithExceptionWrong(UserEntity entity) {
log.info("createSubUserWithExceptionWrong start");
userRepository.save(entity);
throw new RuntimeException("invalid status");
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.