SPRINGBOOT 常用配置(REDIS,JSON,Schedule,启动执行)

SPRINGBOOT 常用配置(REDIS,JSON,Schedule,启动执行)

JSON

@Configuration
public class JacksonConfiguration {
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper =  JsonUtil.newObjectMapper();
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        return objectMapper;
    }
}

REDIS

@Slf4j
@Configuration
@EnableCaching
@AutoConfigureAfter(RedisAutoConfiguration.class)
@EnableAutoConfiguration
public class RedisConfiguration {

    @Resource
    private Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer;

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration config = getRedisCacheConfigurationWithTtl(1200); // 默认缓存1200秒
        RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.
                RedisCacheManagerBuilder.fromConnectionFactory(redisConnectionFactory);
        return builder.transactionAware()
                .cacheDefaults(config)
                .withInitialCacheConfigurations(getRedisCacheConfigurationMap())
                .build();
    }

    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())).//设置 key为string序列化
                serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer) //设置value为json序列化
        ).entryTtl(Duration.ofSeconds(seconds)).disableCachingNullValues();//不缓存空值
        return config;
    }

    private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
        Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
        redisCacheConfigurationMap.put("GEO_INFO", this.getRedisCacheConfigurationWithTtl(3000));
        return redisCacheConfigurationMap;
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value
        System.out.println(jackson2JsonRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        // 使用StringRedisSerializer序列化反序列化redis的key
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    /**
     * description: 默认的redis value序列话
     * time: 5/26/2019 20:19
     * @author xin-bing
     * @version 1.0
     * @param
     * @return org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer
     */
    @Bean
    public Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer() {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = JsonUtil.newObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        return jackson2JsonRedisSerializer;
    }
}
spring:
  redis:
    #数据库索引
    database: 2
    host: IP
    port: PROT
    password: 密码
    timeout: 5000ms
    cache:
      redis:
        cache-null-values: true

Schedule定时任务

@Configuration
public class ScheduleConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(8,
                new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build());
        taskRegistrar.setScheduler(executorService);
    }
}

日期格式化

@Configuration
public class SpringConverterConfiguration {

    /**
     * description: request param convert to LocalDateTime
     * time: 4/20/2019 09:01
     *
     * @return org.springframework.core.convert.converter.Converter<java.lang.String, java.time.LocalDateTime>
     * @author xin-bing
     * @version 1.0
     */
    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter() {
        return new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert(String source) {
                if (StringUtils.isBlank(source)) {
                    return null;
                }
                // just judging source length for choice witch formatter
                if (source.length() == 10) {
                    LocalDate localDate = LocalDate.parse(source, DateTimeFormatters.STANDARD_DATE_FORMATTER);
                    return LocalDateTime.from(localDate.atStartOfDay());
                }
                if (source.length() == 19) {
                    return LocalDateTime.parse(source, DateTimeFormatters.STANDARD_DATE_TIME_FORMATTER);
                } else {
                    throw new IllegalArgumentException("unsupported datetime formatter");
                }
            }
        };
    }

    /**
     * description: request param convert to LocalDate
     * time: 4/20/2019 09:11
     *
     * @return org.springframework.core.convert.converter.Converter<java.lang.String, java.time.LocalDate>
     * @author xin-bing
     * @version 1.0
     */
    @Bean
    public Converter<String, LocalDate> localDateConverter() {
        return new Converter<String, LocalDate>() {
            @Override
            public LocalDate convert(String source) {
                if (StringUtils.isBlank(source)) {
                    return null;
                }
                if (source.length() == 10) {
                    return LocalDate.parse(source, DateTimeFormatters.STANDARD_DATE_FORMATTER);
                }
                if (source.length() == 19) {
                    return LocalDateTime.parse(source, DateTimeFormatters.STANDARD_DATE_TIME_FORMATTER).toLocalDate();
                } else {
                    throw new IllegalArgumentException("unsupported datetime formatter");
                }
            }
        };
    }

    /**
     * description: request param convert to LocalTime
     * time: 4/20/2019 09:12
     *
     * @return org.springframework.core.convert.converter.Converter<java.lang.String, java.time.LocalTime>
     * @author xin-bing
     * @version 1.0
     */
    @Bean
    public Converter<String, LocalTime> localTimeConverter() {
        return new Converter<String, LocalTime>() {
            @Override
            public LocalTime convert(String source) {
                if (StringUtils.isBlank(source)) {
                    return null;
                }
                if (source.length() == 19) {
                    return LocalTime.parse(source, DateTimeFormatters.STANDARD_DATE_TIME_FORMATTER);
                } else if (source.length() == 5) {
                    return LocalTime.parse(source, DateTimeFormatter.ofPattern("HH:mm"));
                }
                return LocalTime.parse(source, DateTimeFormatters.STANDARD_TIME_FORMATTER);
            }
        };
    }
}
public interface DateTimeFormatters {
    DateTimeFormatter STANDARD_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    DateTimeFormatter STANDARD_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    DateTimeFormatter STANDARD_TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");
    DateTimeFormatter YYYYMMDDHHMM5S = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
}

服务器启动执行

/**
 * 服务器启动执行
 */
@Order(value = 1)
@Slf4j
@Component
public class StartComponent implements ApplicationRunner {

    @Resource
    private UserService userService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
//        userService.wxToke();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值