当前位置:   article > 正文

JAVA笔记-SpringBoot的使用_清除springcontextholder中的applicationcontext:root web

清除springcontextholder中的applicationcontext:root webapplicationcontext: st

目录

一、常用注解

二、启动应用

四、Hibernate Validator的使用

五、xml和实体转换(也可用使用xstream)

六、HttpServletRequest

七、从IOC中获取Bean

八、@Qualifier("XXX")注解

九、过滤器(Filter)和拦截器(Interceptor)

十、springcache + redis的使用

十一、springboot i18n国际化

十二、springboot 自定义错误页面

十三、测试类

十四、统一配置接收参数空转null

十五、spring.factories

十六、RedisTemplate的使用

十七、Websocket 配置

十八、Redisson 配置


一、常用注解

    1:@Resource和@AutoWried
       @Resource和@Autowired注解都是用来实现依赖注入的。只是@AutoWried按by type自动注入,而@Resource默认按byName自动注入
        @Resource有两个重要属性,分别是name和type
        spring将name属性解析为bean的名字,而type属性则被解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,如果使用type属性则使用byType的自动注入策略。如果都没有指定,则通过反射机制使用byName自动注入策略

    2:@JsonFormat和@DateTimeFormat
        @JsonFormat用于出参时格式换@DateTimeFormat用于入参时格式化
        @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")

    3:@PostConstruct和@PreDestroy
        javaEE5引入用于Servlet生命周期的注解,实现Bean初始化之前和销毁之前的自定义操作,也可以做初始化init()的一些操作。
        使用此注解会影响服务启动时间

  1. // 用法一:动态变量获取并赋值给静态变量,减少了@Value的多次注入
  2. @Component
  3. public class SystemConstant {
  4. public static String env;
  5. @Value("${spring.profiles.active}")
  6. public String environment;
  7. @PostConstruct
  8. public void initialize() {
  9. System.out.println("初始化环境...");
  10. env= this.environment;
  11. }
  12. }
  13. // 用法二:将注入的Bean赋值给静态变量,减少依赖注入
  14. @Component
  15. public class RedisUtil {
  16. private static RedisTemplate<Object, Object> redisTemplates;
  17. @Autowired
  18. private RedisTemplate<Object, Object> redisTemplate;
  19. @PostConstruct
  20. public void initialize() {
  21. redisTemplates = this.redisTemplate;
  22. }
  23. }

    4:@EnableAspectJAutoProxy(proxyTargetClass = false, exposeProxy = true)
        解决同类方法调用时异步@Async和事务@Transactional不生效问题,没有用到代理类导致
        参数proxyTargetClass控制aop的具体实现方式cglib或java的Proxy,默认为false(java的Proxy)
        参数exposeProxy控制代理的暴露方式,解决内部调用不能使用代理的场景,默认为false
        使用AopContext.currentProxy()获取一个代理类,然后用代理类再去调用就好了

  1. // serviceImpl文件
  2. @Async
  3. @TargetDataSource("db1")
  4. @Override
  5. public void do(String value) {
  6. // 动态切换数据源要注意一个问题,就是在开启事物之前要先切换成需要的数据源,不要在开启事物之后在切换数据源不然会切换失败,因为一个事物的开启是建立在与一个数据源建立连接的基础上开启的所以如果先开启事物然后再切换数据源会报错,切换会失败
  7. ((Service) AopContext.currentProxy()).dosomething(value);
  8. }
  9. @Transactional
  10. @Override
  11. public void dosomething(String value) {
  12. //dosomething()
  13. }
  14. // 注入自己的方式无需开启注解
  15. @Autowired
  16. Service service;
  17. @Async
  18. @TargetDataSource("db1")
  19. @Override
  20. public void do(String value) {
  21. service.dosomething(value);
  22. }
  23. @Transactional
  24. @Override
  25. public void dosomething(String value) {
  26. //dosomething()
  27. }
  28. // 获取当前Bean的方式无需开启注解(使用hutool SpringUtil 或自己封装一个SpringUtil)
  29. @Async
  30. @TargetDataSource("db1")
  31. @Override
  32. public void do(String value) {
  33. currentBean().dosomething(value);
  34. }
  35. @Transactional
  36. @Override
  37. public void dosomething(String value) {
  38. //dosomething()
  39. }
  40. private Service currentBean() {
  41. return SpringUtil.getBean(Service.class);
  42. }
  43. // 反射调用也可用不用开启注解
  44. @Autowired
  45. Service service;
  46. @Async
  47. @TargetDataSource("db1")
  48. @Override
  49. public void do(String value) {
  50. currentClazz().getMethod("dosomething").invoke(service);
  51. currentClazz().getMethod("dosomething").invoke(currentBean());
  52. currentClazz().getMethod("dosomething").invoke(currentProxy());
  53. }
  54. @Transactional
  55. @Override
  56. public void dosomething(String value) {
  57. //dosomething()
  58. }
  59. private Class<Service> currentClazz() {
  60. return Service.class;
  61. }

二、启动应用

    1:maven方式
        mvn spring-boot:run -Dspring-boot.run.profiles=xxx
    2:java -jar方式
        java -server -Xms128m -Xmx256m -Dserver.port=8080 -jar xxx.jar --spring.profiles.active=dev
    3:docker run方式(已经打好镜像)
        环境变量:docker run -d -p 8080:8080 --name xx -e "SPRING_PROFILES_ACTIVE=dev" images:tag
        启动参数(使用ENTRYPOINT []/CMD []时有效):docker run -d -p 8080:8080 --name xx images:tag --spring.profiles.active=dev
        参数加载优先级:配置文件<环境变量<JVM系统变量(-D)<命令行参数(--)
    4:docker-compose方式

  1. #V2.0
  2. environment:
  3. TZ:Asia/Shanghai
  4. JAVA_OPTS: -Dserver.port=8180
  5. JAVA_OPT_EXT: -server -Xms64m -Xmx64m -Xmn64m
  6. #V3.0
  7. environment:
  8. - TZ=Asia/Shanghai
  9. - JAVA_OPTS=-server -Dserver.port=8180 -XX:MetaspaceSize=64m -XX:MaxMetaspaceSize=128m -Xms128m -Xmx256m -Xmn128m -Xss256k -XX:SurvivorRatio=8 -XX:+UseConcMarkSweepGC
  10. # rocketMq配置- JAVA_OPT_EXT= -server -Xms128m -Xmx128m -Xmn128m

三、Hibernate Validator的使用

    1:常用注解
        @NotNull                不能为null
        @AssertTrue         必须为true
        @AssertFalse        必须为false
        @Min                     必须为数字,其值大于或等于指定的最小值
        @Max                    必须为数字,其值小于或等于指定的最大值
        @DecimalMin        必须为数字,其值大于或等于指定的最小值
        @DecimalMax       必须为数字,其值小于或等于指定的最大值
        @Size                   集合的长度
        @Digits                 必须为数字,其值必须再可接受的范围内
        @Past                   必须是过去的日期
        @Future                必须是将来的日期
        @Pattern               必须符合正则表达式
        @Email                  必须是邮箱格式
        @Length                长度范围
        @NotEmpty            不能为null,长度大于0
        @Range                元素的大小范围
        @NotBlank            不能为null,trim()后字符串长度大于0(限字符串)
    2:注解校验

  1. # 使用
  2. @RestController
  3. @Validated
  4. public class ValidateController {
  5. @RequestMapping(value = "/test", method = RequestMethod.GET)
  6. public String paramCheck(@Length(min = 10) @RequestParam String name) {}
  7. @RequestMapping(value = "/person", method = RequestMethod.POST)
  8. public void add(@RequestBody @Valid Person person) {}
  9. }
  10. # 配置快速校验返回
  11. @Bean
  12. public Validator validator(){
  13. ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
  14. .configure()
  15. // true 快速失败返回模式 false 普通模式.failFast(true)
  16. .addProperty( "hibernate.validator.fail_fast", "true" )
  17. .buildValidatorFactory();
  18. return validatorFactory.getValidator();
  19. }

    3:手动校验
        一般我们在实体上加注解就可以实现入参的校验,但是如果在service层来进行校验的话也可以使用如下方式

  1. // 手动校验入参
  2. Set<ConstraintViolation<@Valid BudgetGetParamDTO>> validateSet = Validation.buildDefaultValidatorFactory()
  3. .getValidator()
  4. .validate(paramDTO, Default.class);
  5. if (!CollectionUtils.isEmpty(validateSet)) {
  6. // String messages = validateSet.stream().map(ConstraintViolation::getMessage).reduce((m1, m2) -> m1 + ";" + m2).orElse("参数输入有误!");
  7. // Iterator<ConstraintViolation<BudgetGetParamDTO>> it = validateSet.iterator();
  8. // List<String> errors = new ArrayList<>();
  9. // while (it.hasNext()) {
  10. // ConstraintViolation<BudgetGetParamDTO> cv = it.next();
  11. // errors.add(cv.getPropertyPath() + ": " + cv.getMessage());
  12. // }
  13. String messages = validateSet.iterator().next().getPropertyPath() + ": " + validateSet.iterator().next().getMessage();
  14. return ResultUtil.error(0, messages);
  15. }

    4:自定义校验器

  1. # 使用@Pattern拓展一个校验器
  2. @ConstraintComposition(CompositionType.OR)
  3. //@Pattern(regexp = "1[3|4|5|7|8][0-9]\\d{8}")
  4. @Pattern(regexp = "1\\d{10}")
  5. @Null
  6. @Length(min = 0, max = 0)
  7. @Documented
  8. @Constraint(validatedBy = {})
  9. @Target({METHOD, FIELD, CONSTRUCTOR, PARAMETER})
  10. @Retention(RUNTIME)
  11. @ReportAsSingleViolation
  12. public @interface PhoneValid {
  13. String message() default "手机号校验错误";
  14. Class<?>[] groups() default {};
  15. Class<? extends Payload>[] payload() default {};
  16. }
  17. # 自定义一个校验器
  18. public enum CaseMode {
  19. UPPER,
  20. LOWER;
  21. }
  22. @Target( { ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
  23. @Retention(RetentionPolicy.RUNTIME)
  24. @Constraint(validatedBy = CheckCaseValidator.class)
  25. @Documented
  26. public @interface CheckCase {
  27. String message() default "";
  28. Class<?>[] groups() default {};
  29. Class<? extends Payload>[] payload() default {};
  30. CaseMode value();
  31. }
  32. public class CheckCaseValidator implements ConstraintValidator<CheckCase, String> {
  33. private CaseMode caseMode;
  34. public void initialize(CheckCase checkCase) {
  35. this.caseMode = checkCase.value();}
  36. public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
  37. if (s == null) {return true;}
  38. if (caseMode == CaseMode.UPPER) {
  39. return s.equals(s.toUpperCase());
  40. } else {
  41. return s.equals(s.toLowerCase());}
  42. }
  43. }

    5:分组校验

  1. @Data
  2. public class DemoDto {
  3. public interface Default {}
  4. public interface Update {}
  5. @NotEmpty(message = "名称不能为空")
  6. private String name;
  7. @Length(min = 5, max = 25, message = "key的长度为5-25" ,groups = Default.class )
  8. private String key;
  9. @Pattern(regexp = "[012]", message = "无效的状态标志",groups = {Default.class,Update.class} )
  10. private String state;
  11. }
  12. @RequestMapping("test2")
  13. public String test2(@Validated(value = DemoDto.Default.class) @RequestBody DemoDto dto){}
  14. @RequestMapping("test4")
  15. public String test4(@Validated(value = {DemoDto.Default.class,DemoDto.Update.class}) @RequestBody DemoDto dto){}

四、xml和实体转换(也可用使用xstream)

  1. @Data
  2. @XmlAccessorType(XmlAccessType.FIELD)
  3. @XmlRootElement(name = "QueryResult")
  4. public class RetDTO {
  5. @ApiModelProperty(value = "返回信息", notes = "MSG", example = "MSG")
  6. private String MSG;
  7. @ApiModelProperty(value = "是否成功 Y成功 N失败", notes = "Y", example = "Y")
  8. private String BSUCCESS;
  9. @ApiModelProperty(value = "结果", notes = "[]", example = "[]")
  10. private InfosDTO INFOS;
  11. }
  12. @Data
  13. @XmlAccessorType(XmlAccessType.FIELD)
  14. @XmlRootElement(name = "INFO")
  15. public class InfosDTO {
  16. @ApiModelProperty(value = "结果集", notes = "[]", example = "[]")
  17. private List<ItemRetDTO> INFO;
  18. }
  19. @Data
  20. @XmlAccessorType(XmlAccessType.FIELD)
  21. @XmlRootElement(name = "INFO")
  22. public class ItemRetDTO implements Serializable {
  23. @ApiModelProperty(value = "号", notes = "code", example = "code")
  24. @XmlElement(name = "CODE")
  25. private String code;
  26. }
  27. // xml转实体
  28. String objStr = re.getBody().substring(re.getBody().indexOf("<QueryResult>"), re.getBody().indexOf("</QueryResult>")) + "</QueryResult>";
  29. JAXBContext context = JAXBContext.newInstance(RetDTO.class);
  30. Unmarshaller unmarshaller = context.createUnmarshaller();
  31. RetDTO obj = (RetDTO) unmarshaller.unmarshal(new StringReader(objStr));
  32. // 实体转xml
  33. String result = null;
  34. JAXBContext context = JAXBContext.newInstance(obj.getClass());
  35. Marshaller marshaller = context.createMarshaller();
  36. // 指定是否使用换行和缩排对已编组 XML 数据进行格式化的属性名称。
  37. marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  38. marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
  39. StringWriter writer = new StringWriter();
  40. marshaller.marshal(obj, writer);
  41. result = writer.toString();
  42. return result;

五、HttpServletRequest

    可以把servletRequest转换 HttpServletRequest httpRequest = (HttpServletRequest) servletRequest这样比ServletRequest多了一些针对于Http协议的方法。 例如:getHeader(), getMethod() , getSession()

六、从IOC中获取Bean

  1. package com.bootbase.common.core.util;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.beans.factory.DisposableBean;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.ApplicationContextAware;
  6. import org.springframework.context.ApplicationEvent;
  7. import org.springframework.context.annotation.Lazy;
  8. import org.springframework.stereotype.Service;
  9. /**
  10. * @Description: 常用工具类
  11. */
  12. @Slf4j
  13. @Service
  14. @Lazy(false)
  15. public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
  16. private static ApplicationContext applicationContext = null;
  17. /**
  18. * 取得存储在静态变量中的ApplicationContext.
  19. */
  20. public static ApplicationContext getApplicationContext() {
  21. return applicationContext;
  22. }
  23. /**
  24. * 实现ApplicationContextAware接口, 注入Context到静态变量中.
  25. */
  26. @Override
  27. public void setApplicationContext(ApplicationContext applicationContext) {
  28. SpringContextHolder.applicationContext = applicationContext;
  29. }
  30. /**
  31. * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
  32. */
  33. @SuppressWarnings("unchecked")
  34. public static <T> T getBean(String name) {
  35. return (T) applicationContext.getBean(name);
  36. }
  37. /**
  38. * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
  39. */
  40. public static <T> T getBean(Class<T> requiredType) {
  41. return applicationContext.getBean(requiredType);
  42. }
  43. /**
  44. * 清除SpringContextHolder中的ApplicationContext为Null.
  45. */
  46. public static void clearHolder() {
  47. if (log.isDebugEnabled()) {
  48. log.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
  49. }
  50. applicationContext = null;
  51. }
  52. /**
  53. * 发布事件
  54. *
  55. * @param event
  56. */
  57. public static void publishEvent(ApplicationEvent event) {
  58. if (applicationContext == null) {
  59. return;
  60. }
  61. applicationContext.publishEvent(event);
  62. }
  63. /**
  64. * 实现DisposableBean接口, 在Context关闭时清理静态变量.
  65. */
  66. @Override
  67. public void destroy() throws Exception {
  68. SpringContextHolder.clearHolder();
  69. }
  70. }
  71. // 使用 (XxxService) SpringContextHolder.getBean("xxxServiceImpl")

七、@Qualifier("XXX")注解

    当一个接口有2个不同实现时,使用@Autowired注解时会报会报错,此时可以结合@Qualifier("XXX")注解来解决这个问题。@Autowired和@Qualifier结合使用时,自动注入的策略会从byType转变成byName,还有就是使用@Primary可以理解为默认优先选择,同时不可以同时设置多个。

八、过滤器(Filter)和拦截器(Interceptor)

    过滤器赖于servlet容器,实例只能在容器初始化时调用一次,是用来做一些过滤操作,获取我们想要获取的数据,比如:在Javaweb中,对传入的request、response提前过滤掉一些信息,或者提前设置一些参数,然后再传入servlet或者Controller进行业务逻辑操作。通常用的场景是:在过滤器中修改字符编码(CharacterEncodingFilter)、在过滤器中修改HttpServletRequest的一些参数(XSSFilter(自定义过滤器)),如:过滤低俗文字、危险字符等。
    拦截器依赖于web框架,基于Java的反射机制,属于面向切面编程(AOP)的一种运用,就是在service或者一个方法前,调用一个方法,或者在方法后,调用一个方法,比如动态代理就是拦截器的简单实现,在调用方法前打印出字符串(或者做其它业务逻辑的操作),也可以在调用方法后打印出字符串,甚至在抛出异常的时候做业务逻辑的操作。由于拦截器是基于web框架的调用,因此可以使用Spring的依赖注入(DI)进行一些业务操作,同时一个拦截器实例在一个controller生命周期之内可以多次调用。拦截器可以对静态资源的请求进行拦截处理。
    两者的本质区别:拦截器(Interceptor)是基于Java的反射机制,而过滤器(Filter)是基于函数回调。从灵活性上说拦截器功能更强大些,Filter能做的事情,都能做,而且可以在请求前,请求后执行,比较灵活。Filter主要是针对URL地址做一个编码的事情、过滤掉没用的参数、安全校验(比较泛的,比如登录不登录之类),太细的话,还是建议用interceptor。不过还是根据不同情况选择合适的

九、springcache + redis的使用

  1. // 添加依赖
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-cache</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-data-redis</artifactId>
  9. </dependency>
  10. // 配置
  11. @EnableCaching // 注解会自动化配置合适的缓存管理器(CacheManager)
  12. @Configuration
  13. @AllArgsConstructor
  14. @AutoConfigureBefore(RedisAutoConfiguration.class)
  15. public class RedisTemplateConfig {
  16. private final RedisConnectionFactory factory;
  17. @Bean
  18. public RedisTemplate<String, Object> redisTemplate() {
  19. RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
  20. redisTemplate.setKeySerializer(new StringRedisSerializer());
  21. redisTemplate.setHashKeySerializer(new StringRedisSerializer());
  22. redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
  23. redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
  24. redisTemplate.setConnectionFactory(factory);
  25. return redisTemplate;
  26. }
  27. @Bean
  28. public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
  29. return redisTemplate.opsForHash();
  30. }
  31. @Bean
  32. public ValueOperations<String, String> valueOperations(RedisTemplate<String, String> redisTemplate) {
  33. return redisTemplate.opsForValue();
  34. }
  35. @Bean
  36. public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
  37. return redisTemplate.opsForList();
  38. }
  39. @Bean
  40. public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
  41. return redisTemplate.opsForSet();
  42. }
  43. @Bean
  44. public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
  45. return redisTemplate.opsForZSet();
  46. }
  47. // @Bean // @EnableCaching也会自动注入
  48. // public CacheManager redisCacheManager() {
  49. // RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate());
  50. // cacheManager.setDefaultExpiration(300);
  51. // cacheManager.setLoadRemoteCachesOnStartup(true); // 启动时加载远程缓存
  52. // cacheManager.setUsePrefix(true); //是否使用前缀生成器
  53. // // 这里可进行一些配置 包括默认过期时间 每个cacheName的过期时间等 前缀生成等等
  54. // return cacheManager;
  55. //}
  56. }
  57. // 使用
  58. @Cacheable(value = "models", key = "#testModel.name", condition = "#testModel.address != '' ")
  59. value (也可使用 cacheNames): 可看做命名空间,表示存到哪个缓存里了。
  60. key: 表示命名空间下缓存唯一key,使用Spring Expression Language(简称SpEL)生成。
  61. condition: 表示在哪种情况下才缓存结果(对应的还有unless,哪种情况不缓存),同样使用SpEL
  62. sync:是否同步
  63. @CacheEvict(value = "models", allEntries = true)@CacheEvict(value = "models", key = "#name")
  64. value:指定命名空间
  65. allEntries:清空命名空间下缓存
  66. key:删除指定key缓存
  67. beforeInvocation:bool 在调用前清除缓存
  68. @CacheEvict和@Scheduled(fixedDelay = 10000)同时用
  69. 10s删除一次
  70. @CachePut(value = "models", key = "#name")刷新缓存

十、springboot i18n国际化

    1:返回信息国际化

  1. # Resource 文件夹下添加多语言文件message.propertiies(默认) message_en_US.propertiies message_zh_CN.propertiies
  2. # 在application.yml中添加配置多语言文件地址
  3. spring:
  4. messages:
  5. encoding: UTF-8
  6. basename: i18n/messages
  7. # 创建读取配置内容的工具类
  8. @Component
  9. public class LocaleMessageSourceService {
  10. @Resource
  11. private MessageSource messageSource;
  12. public String getMessage(String code) {
  13. return this.getMessage(code, new Object[]{});}
  14. public String getMessage(String code, String defaultMessage) {
  15. return this.getMessage(code, null, defaultMessage);}
  16. public String getMessage(String code, String defaultMessage, Locale locale) {
  17. return this.getMessage(code, null, defaultMessage, locale);}
  18. public String getMessage(String code, Locale locale) {
  19. return this.getMessage(code, null, "", locale);}
  20. public String getMessage(String code, Object[] args) {
  21. return this.getMessage(code, args, "");}
  22. public String getMessage(String code, Object[] args, Locale locale) {
  23. return this.getMessage(code, args, "", locale);}
  24. public String getMessage(String code, Object[] args, String defaultMessage) {
  25. Locale locale = LocaleContextHolder.getLocale();
  26. return this.getMessage(code, args, defaultMessage, locale);}
  27. public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) {
  28. return messageSource.getMessage(code, args, defaultMessage, locale);}
  29. }
  30. # 使用
  31. @Autowired
  32. privateLocaleMessageSourceService localeMessageSourceService;
  33. localeMessageSourceService.getMessage("key"); // 只能读取i18n/messages**文件中的key
  34. # 请求
  35. 发请求时在请求头加上Accept-Language zh-CN/zh-TW/zh-HK/en-US 和配置文件对应这里就不能为zh或en

    2:Vakidator校验国际化

  1. # 在Resources目录下创建ValidationMessages.properties(默认) ValidationMessages_zh_CN.properties ValidationMessages_en_US.properties
  2. # 默认情况下@Validated的message必须放在Resources下的ValidationMessages名称不可修改,如果想自定义可用通过配置修改
  3. @Resource
  4. private MessageSource messageSource;
  5. @NotNull
  6. @Bean
  7. public Validator getValidator() {
  8. LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
  9. // 这里使用系统i18n也就是 spring.messages.basename
  10. validator.setValidationMessageSource(this.messageSource);
  11. return validator;
  12. }
  13. 或(如果配置了校验的快速失败返回应和快速失败返回配置在一起)
  14. @Bean
  15. public Validator validator(){
  16. ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
  17. .configure()
  18. .messageInterpolator(new LocaleContextMessageInterpolator(new ResourceBundleMessageInterpolator(new MessageSourceResourceBundleLocator(this.messageSource))))
  19. // true 快速失败返回模式 false 普通模式.failFast(true)
  20. .addProperty( "hibernate.validator.fail_fast", "true" )
  21. .buildValidatorFactory();
  22. return validatorFactory.getValidator();
  23. }
  24. # 使用
  25. @NotBlank(message = "{key}")
  26. private String name;
  27. # 请求
  28. 发请求时在请求头加上Accept-Language zh-CN/zh-TW/zh-HK/en-US 和配置文件对应这里就不能为zh或en

    3:统一异常处理

  1. @Slf4j
  2. @RestControllerAdvice
  3. public class GlobalExceptionHandler {
  4. @ExceptionHandler(Exception.class)
  5. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  6. public R exception(Exception e) {
  7. log.error("全局异常信息 ex={}", e.getMessage(), e);
  8. return R.failed(e.getMessage());}
  9. @ExceptionHandler(BusinessException.class)
  10. @ResponseStatus(HttpStatus.OK)
  11. public R exception(BusinessException e) {
  12. log.error("业务处理异常 ex={}", e.getMessage(), e);
  13. return R.restResult(null, e.getCode(), e.getMessage());}
  14. @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
  15. @ResponseStatus(HttpStatus.BAD_REQUEST)
  16. public R bodyValidExceptionHandler(MethodArgumentNotValidException exception) {
  17. List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
  18. log.warn(fieldErrors.get(0).getDefaultMessage());
  19. return R.failed(fieldErrors.get(0).getDefaultMessage());}
  20. @ExceptionHandler({ConstraintViolationException.class})
  21. @ResponseStatus(HttpStatus.BAD_REQUEST) // 参数校验错误
  22. public R paramValidExceptionHandler(ConstraintViolationException exception) {
  23. Set<ConstraintViolation<?>> fieldErrors = exception.getConstraintViolations();
  24. List<ConstraintViolation<?>> errors = new ArrayList<>(fieldErrors);
  25. log.warn(errors.get(0).getMessage());
  26. return R.failed(errors.get(0).getMessage());}
  27. @ExceptionHandler(HttpMessageNotReadableException.class)
  28. @ResponseStatus(HttpStatus.BAD_REQUEST) // 请求方式错误 json少body
  29. public R normalException(HttpMessageNotReadableException e) {
  30. String msg = e.getMessage();
  31. log.warn("校验异常 ex={}", msg);
  32. return R.failed(msg);}
  33. }

十一、springboot 自定义错误页面

  1. @ApiIgnore
  2. @Controller
  3. public class ErrorController extends BasicErrorController {
  4. @Autowired
  5. public ErrorController(ErrorAttributes errorAttributes,
  6. ServerProperties serverProperties,
  7. List<ErrorViewResolver> errorViewResolvers) {
  8. super(errorAttributes, serverProperties.getError(), errorViewResolvers);
  9. }
  10. // @Override
  11. // public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
  12. // HttpStatus status = getStatus(request);
  13. // // 获取 Spring Boot 默认提供的错误信息,然后添加一个自定义的错误信息
  14. // Map<String, Object> model = getErrorAttributes(request,
  15. // isIncludeStackTrace(request, MediaType.TEXT_HTML));
  16. // model.put("msg", "出错啦++++++");
  17. // // resource/templates 目录下创建一个 errorPage.html 文件作为视图页面${code}
  18. // ModelAndView modelAndView = new ModelAndView("errorPage", model, status);
  19. // return modelAndView;
  20. // }
  21. @Override // ajax请求时不再返回错误页面,页面请求还是返回错误页
  22. public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
  23. Map<String, Object> errorAttributes = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
  24. HttpStatus status = getStatus(request);
  25. // 获取错误信息 message/error
  26. String message = errorAttributes.get("message").toString();
  27. String path = errorAttributes.get("path").toString();
  28. Map<String, Object> retmap = new HashMap<>();
  29. BeanUtil.copyProperties(R.failed(path, message), retmap);
  30. return new ResponseEntity<>(retmap, status);
  31. }
  32. }

十二、测试类

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = XxxApplication.class)
    public class XxxApplicationTests {
    @Test
    public void contextLoads() {}
    }

十三、统一配置接收参数空转null

  1. @ControllerAdvice
  2. public class GlobalControllerAdiviceConfig {
  3. // GET参数:WebDataBinder是用来绑定请求参数到指定的属性编辑器,可以继承WebBindingInitializer来实现一个全部controller共享的dataBiner Java代码
  4. @InitBinder
  5. public void dataBind(WebDataBinder binder) {
  6. binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
  7. }
  8. // 处理Post报文体 没有配置ObjectMapper的Bean时使用此方式
  9. @Bean
  10. public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
  11. return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder
  12. .deserializerByType(String.class, new StdScalarDeserializer<String>(String.class) {
  13. @Override
  14. public String deserialize(JsonParser jsonParser, DeserializationContext ctx) throws IOException {
  15. // 重点在这儿:如果为空白则返回null
  16. String value = jsonParser.getValueAsString();
  17. if (value == null || "".equals(value.trim())) {
  18. return null;
  19. }
  20. return value.trim();
  21. }
  22. });
  23. }
  24. // 存在ObjectMapper的Bean时直接在Bean中配置
  25. // 此方式或@Bean @Primary会覆盖默认配置
  26. @Bean
  27. public ObjectMapper getObjectMapper() {
  28. ObjectMapper objectMapper = new ObjectMapper();
  29. JavaTimeModule javaTimeModule = new JavaTimeModule();
  30. javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")));
  31. javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
  32. javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
  33. javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
  34. javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
  35. javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
  36. javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
  37. // javaTimeModule只能手动注册,参考https://github.com/FasterXML/jackson-modules-java8
  38. objectMapper.registerModule(javaTimeModule);
  39. // 忽略json字符串中不识别的属性
  40. objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  41. // 忽略无法转换的对象
  42. objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
  43. // 统一配置接收参数空转null
  44. SimpleModule strModule = new SimpleModule();
  45. strModule.addDeserializer(String.class, new StdScalarDeserializer<String>(String.class) {
  46. @Override
  47. public String deserialize(JsonParser jsonParser, DeserializationContext ctx) throws IOException {
  48. // 重点在这儿:如果为空白则返回null
  49. String value = jsonParser.getValueAsString();
  50. if (value == null || "".equals(value.trim())) {
  51. return null;
  52. }
  53. return value.trim();
  54. }
  55. });
  56. objectMapper.registerModule(strModule);
  57. // 对于String类型,使用objectMapper.registerModule(module)的方式;对于POJOs类型,使用objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)的方式;
  58. // objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
  59. return objectMapper;
  60. }
  61. }
  62. // 不要覆盖默认配置
  63. // 我们通过实现Jackson2ObjectMapperBuilderCustomizer接口并注册到容器,进行个性化定制,Spring Boot不会覆盖默认ObjectMapper的配置,而是进行了合并增强,具体还会根据Jackson2ObjectMapperBuilderCustomizer实现类的Order优先级进行排序,因此上面的JacksonConfig配置类还实现了Ordered接口。
  64. // 默认的Jackson2ObjectMapperBuilderCustomizerConfiguration优先级是0,因此如果我们想要覆盖配置,设置优先级大于0即可
  65. // 在SpringBoot2环境下,不要将自定义的ObjectMapper对象注入容器,这样会将原有的ObjectMapper配置覆盖!
  66. @Component
  67. public class JacksonConfig implements Jackson2ObjectMapperBuilderCustomizer, Ordered {
  68. @Override
  69. public void customize(Jackson2ObjectMapperBuilder builder) {
  70. // 设置java.util.Date时间类的序列化以及反序列化的格式
  71. builder.simpleDateFormat(dateTimeFormat);
  72. // JSR 310日期时间处理
  73. JavaTimeModule javaTimeModule = new JavaTimeModule();
  74. DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateTimeFormat);
  75. javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter));
  76. javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(dateTimeFormatter));
  77. DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(dateFormat);
  78. javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(dateFormatter));
  79. javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(dateFormatter));
  80. DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(timeFormat);
  81. javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(timeFormatter));
  82. javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(timeFormatter));
  83. builder.modules(javaTimeModule);
  84. // 全局转化Long类型为String,解决序列化后传入前端Long类型精度丢失问题
  85. builder.serializerByType(BigInteger.class, ToStringSerializer.instance);
  86. builder.serializerByType(Long.class,ToStringSerializer.instance);
  87. }
  88. @Override
  89. public int getOrder() {
  90. return 1;
  91. }
  92. }

十四、spring.factories

    如果你有探索过这些Starter的原理,那你一定知道Spring Boot并没有消灭这些原本你要配置的Bean,而是将这些Bean做成了一些默认的配置类,同时利用/META-INF/spring.factories这个文件来指定要加载的默认配置。这样当Spring Boot应用启动的时候,就会根据引入的各种Starter中的/META-INF/spring.factories文件所指定的配置类去加载Bean
    对于自定义的jar包如果想让引入的工程加载jar中的Bean我们就需要仿照Starter的方式把相关的Bean放入此文件中
    Spring Boot2.7发布后不再推荐使用这种方式,3.0后将不支持这种写法
    老写法:org.springframework.boot.autoconfigure.EnableAutoConfiguration=\   com.spring4all.swagger.SwaggerAutoConfiguration
    新写法:创建文件/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports内容为com.spring4all.swagger.SwaggerAutoConfiguration

十五、RedisTemplate的使用

  1. # 引入依赖
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. </dependency>
  6. # 配置
  7. spring:
  8. redis:
  9. password: redis
  10. host: redis
  11. database: 1
  12. # 序列化
  13. @Configuration
  14. public class MyRedisConfig {
  15. @Bean
  16. public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
  17. RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
  18. //参照StringRedisTemplate内部实现指定序列化器
  19. redisTemplate.setConnectionFactory(redisConnectionFactory);
  20. redisTemplate.setKeySerializer(new StringRedisSerializer());
  21. redisTemplate.setHashKeySerializer(new StringRedisSerializer());
  22. // new JdkSerializationRedisSerializer()或new GenericJackson2JsonRedisSerializer()
  23. redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
  24. redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
  25. return redisTemplate;
  26. }
  27. }
  28. # 使用
  29. # opsForValue()-操作字符串;opsForHash()-操作hash;opsForList()-操作list;opsForSet()-操作set;opsForZSet()-操作有序zset
  30. redisTemplate.hasKey(key) // 判断key是否存在
  31. redisTemplate.expire(key, time, TimeUnit.MINUTES) // 指定key的失效时间DAYS HOURS
  32. redisTemplate.getExpire(key) // 根据key获取过期时间
  33. redisTemplate.delete(key) // 根据key删除reids中缓存数据
  34. redisTemplate.opsForValue().set("key1", "value1", 1, TimeUnit.MINUTES)
  35. redisTemplate.opsForValue().set("key2", "value2")
  36. redisTemplate.opsForValue().get("key1").toString()
  37. redisTemplate.opsForList().leftPush("listkey1", list1)
  38. (List<String>) redisTemplate.opsForList().leftPop("listkey1")
  39. redisTemplate.opsForList().rightPush("listkey2", list2)
  40. (List<String>) redisTemplate.opsForList().rightPop("listkey2")
  41. redisTemplate.opsForHash().putAll("map1", map)
  42. redisTemplate.opsForHash().entries("map1")
  43. redisTemplate.opsForHash().values("map1")
  44. redisTemplate.opsForHash().keys("map1")
  45. (String) redisTemplate.opsForHash().get("map1", "key1")
  46. redisTemplate.opsForSet().add("key1", "value1")
  47. Set<String> resultSet = redisTemplate.opsForSet().members("key1")
  48. ZSetOperations.TypedTuple<Object> objectTypedTuple1 = new DefaultTypedTuple<>("zset-5", 9.6)
  49. Set<ZSetOperations.TypedTuple<Object>> tuples = new HashSet<>()
  50. tuples.add(objectTypedTuple1)

十六、Websocket 配置

  1. # 引入依赖
  2. <!-- WebSocket -->
  3. <dependency>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-starter-websocket</artifactId>
  6. </dependency>
  7. # 配置文件
  8. @Configuration
  9. @Slf4j
  10. public class WebSocketConfiguration implements ServletContextInitializer {
  11. /**
  12. * 这个bean的注册,用于扫描带有@ServerEndpoint的注解成为websocket,如果你使用外置的tomcat就不需要该配置文件
  13. */
  14. @Bean
  15. public ServerEndpointExporter serverEndpointExporter() {
  16. return new ServerEndpointExporter();
  17. }
  18. @Override
  19. public void onStartup(ServletContext servletContext) {
  20. log.info("WebSocket:::startup");
  21. }
  22. }
  23. # 操作接口类
  24. public interface SocketSeverService {
  25. /**
  26. * 建立WebSocket连接
  27. * @param session session
  28. * @param userId 用户ID
  29. */
  30. void onOpen(Session session, String userId);
  31. /**
  32. * 发生错误
  33. * @param throwable e
  34. */
  35. void onError(Throwable throwable);
  36. /**
  37. * 连接关闭
  38. */
  39. public void onClose();
  40. /**
  41. * 接收客户端消息
  42. * @param message 接收的消息
  43. */
  44. void onMessage(String message);
  45. /**
  46. * 推送消息到指定用户
  47. * @param userId 用户ID
  48. * @param message 发送的消息
  49. */
  50. void sendMessageByUser(Integer userId, String message);
  51. /**
  52. * 群发消息
  53. * @param message 发送的消息
  54. */
  55. void sendAllMessage(String message);
  56. }
  57. # 操作实现
  58. @ServerEndpoint("/websocket/{userId}")
  59. @Component
  60. @Slf4j
  61. public class WebSocketSeverService implements SocketSeverService {
  62. // 与某个客户端的连接会话,需要通过它来给客户端发送数据
  63. private Session session;
  64. // session集合,存放对应的session
  65. private static final ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<>();
  66. // concurrent包的线程安全Set,用来存放每个客户端对应的WebSocket对象。
  67. private static final CopyOnWriteArraySet<WebSocketSeverService> webSocketSet = new CopyOnWriteArraySet<>();
  68. @OnOpen
  69. @Override
  70. public void onOpen(Session session, @PathParam(value = "userId") String userId) {
  71. log.info("WebSocket:::建立连接中,连接用户ID:{}", userId);
  72. try {
  73. Session historySession = sessionPool.get(userId);
  74. // historySession不为空,说明已经有人登陆账号,应该删除登陆的WebSocket对象
  75. if (historySession != null) {
  76. webSocketSet.remove(historySession);
  77. historySession.close();
  78. }
  79. } catch (IOException e) {
  80. log.error("WebSocket:::重复登录异常,错误信息:" + e.getMessage(), e);
  81. }
  82. // 建立连接
  83. this.session = session;
  84. webSocketSet.add(this);
  85. sessionPool.put(userId, session);
  86. log.info("WebSocket:::建立连接完成,当前在线人数为:{}", webSocketSet.size());
  87. }
  88. @OnError
  89. @Override
  90. public void onError(Throwable throwable) {
  91. log.info("WebSocket:::error:{}", throwable.getMessage());
  92. }
  93. @OnClose
  94. @Override
  95. public void onClose() {
  96. webSocketSet.remove(this);
  97. log.info("WebSocket:::连接断开,当前在线人数为:{}", webSocketSet.size());
  98. }
  99. @OnMessage
  100. @Override
  101. public void onMessage(String message) {
  102. log.info("WebSocket:::收到客户端发来的消息:{}", message);
  103. }
  104. @Override
  105. public void sendMessageByUser(Integer userId, String message) {
  106. log.info("WebSocket:::发送消息,用户ID:" + userId + ",推送内容:" + message);
  107. Session session = sessionPool.get(userId);
  108. try {
  109. session.getBasicRemote().sendText(message);
  110. } catch (IOException e) {
  111. log.error("WebSocket:::推送消息到指定用户发生错误:" + e.getMessage(), e);
  112. }
  113. }
  114. @Override
  115. public void sendAllMessage(String message) {
  116. log.info("WebSocket:::发送消息:{}", message);
  117. for (WebSocketSeverService webSocket : webSocketSet) {
  118. try {
  119. webSocket.session.getBasicRemote().sendText(message);
  120. } catch (IOException e) {
  121. log.error("WebSocket:::群发消息发生错误:" + e.getMessage(), e);
  122. }
  123. }
  124. }
  125. }
  126. # 使用
  127. @Autowired
  128. private SocketSeverService webSocketSeverService;
  129. webSocketSeverService.sendAllMessage(JSONUtil.toJsonStr(msg));
  130. # 前台连接-微信小程序
  131. data: {wx: null,pingInterval: null, lockReconnect: false, timer: null, limit: 0}
  132. reconnect(){
  133. if (this.lockReconnect) return;
  134. this.lockReconnect = true;
  135. clearTimeout(this.timer)
  136. if (this.data.limit<12){
  137. this.timer = setTimeout(() => {
  138. this.linkSocket();
  139. this.lockReconnect = false;
  140. }, 5000);
  141. this.setData({
  142. limit: this.data.limit+1
  143. })
  144. }
  145. },
  146. onShow: function() {
  147. let ws = wx.connectSocket({
  148. url: 'wss://api.shoutouf.com/testapi/websocket/'+this.data.apiData.query.userId,
  149. header:{
  150. 'content-type': 'application/json',
  151. 'Authorization': 'Bearer ' + wx.getStorageSync('access_token')
  152. },
  153. success: (e) => {console.log('ws连接成功', e)},
  154. fail: (e) => {console.log('ws连接失败', e)}
  155. })
  156. ws.onOpen((res) => {
  157. console.log(res)
  158. clearInterval(this.data.pingInterval)
  159. let pingInterval = setInterval(()=> {
  160. let msg={msg:'ping',toUser:'root'}
  161. wx.sendSocketMessage({data:JSON.stringify(msg)})
  162. }, 10000)
  163. this.setData({pingInterval: pingInterval})
  164. })
  165. ws.onMessage((res) => {console.log(222);console.log(res)})
  166. ws.onClose((res) => {console.log(333);this.reconnect()})
  167. ws.onError((res) => {console.log(22);heartCheck.reset();this.reconnect()})
  168. this.setData({ws: ws})
  169. }
  170. }
  171. onUnload: function () {
  172. this.data.ws.close()
  173. clearInterval(this.data.pingInterval)
  174. }
  175. # 前台连接-vue
  176. npm i sockjs-client stompjs
  177. import SockJS from 'sockjs-client';
  178. import Stomp from 'stompjs';
  179. connection() {
  180. let headers = {Authorization: 'Bearer ' + "4cf7d2df-f4a2-4295-b267-03dca1910459"};
  181. // 建立连接对象,这里配置了代理
  182. this.socket = new SockJS('/other/ws', null, {timeout: 10000});
  183. // 连接服务端提供的通信接口,连接以后才可以订阅广播消息和个人消息
  184. // 获取STOMP子协议的客户端对象
  185. this.stompClient = Stomp.over(this.socket);
  186. // 向服务器发起websocket连接
  187. this.stompClient.connect(headers, () => {
  188. this.stompClient.subscribe('/app/topic/pc', function(greeting) {
  189. console.log(greeting, 668);
  190. });
  191. }, err => {console.log("订阅失败")});
  192. }

十七、Redisson 配置

  1. # 引入排除高版本的springdata引入和自己springboot相对于的版本否则报错
  2. # 引入redisson后本身包含redis-starter因此可以不用再引入了
  3. <dependency>
  4. <!--redisson, 包含redis-->
  5. <groupId>org.redisson</groupId>
  6. <artifactId>redisson-spring-boot-starter</artifactId>、、
  7. <version>3.23.4</version>
  8. <exclusions>
  9. <exclusion>
  10. <groupId>org.redisson</groupId>
  11. <artifactId>redisson-spring-data-31</artifactId>
  12. </exclusion>
  13. </exclusions>
  14. </dependency>
  15. <dependency>
  16. <groupId>org.redisson</groupId>
  17. <artifactId>redisson-spring-data-24</artifactId>
  18. <version>3.23.4</version>
  19. </dependency>
  20. # 配置-方式有yaml和文件两种方式
  21. # yaml中redisson其实是字符串所以不支持ENC但是支持表达式,这里的password和host其实是为了加密可以不要直接放在redisson中
  22. # codec是redis的序列化方式因为之前redis时配置的是默认jdk所以redisson也使用jdk,这里也可以使用json不过对于java来说使用redisson默认的Kryo5Codec和Jdk方式比json方式性能要高很多
  23. spring:
  24. redis:
  25. password: ENC(83PKsY3qVKiIX9AehVyniQ==)
  26. host: localhost
  27. redisson:
  28. # 或 file: classpath:xxx.yml
  29. config: |
  30. singleServerConfig:
  31. address: redis://${spring.redis.host}:6379
  32. password: ${spring.redis.password}
  33. codec:
  34. class: "org.redisson.codec.SerializationCodec"
  35. transportMode: "NIO"
  36. lockWatchdogTimeout: 10000 # 看门狗默认30s这里配置10s
  37. @Bean
  38. public RedisTemplate<String, Object> redisTemplate() {
  39. RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
  40. redisTemplate.setConnectionFactory(factory);
  41. // redisTemplate.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
  42. redisTemplate.setKeySerializer(new StringRedisSerializer());
  43. redisTemplate.setHashKeySerializer(new StringRedisSerializer());
  44. redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
  45. redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
  46. return redisTemplate;
  47. }
  48. # 当使用CacheManager操作缓存时一定要配置序列化方式一致不然oauth2会抛出[no body]错误
  49. @Bean
  50. public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
  51. // 解决Redisson引入后查询缓存转换异常的问题
  52. // ObjectMapper om = new ObjectMapper();
  53. // om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  54. // om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
  55. // ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
  56. RedisCacheConfiguration config =
  57. RedisCacheConfiguration.defaultCacheConfig().serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new JdkSerializationRedisSerializer())); //设置序列化器
  58. return RedisCacheManager.builder(redisConnectionFactory)
  59. .cacheDefaults(config)
  60. .build();
  61. }
  62. # 使用
  63. @Autowired
  64. private RedissonClient redissonClient;
  65. RLock lock = redissonClient.getLock("key");
  66. try {
  67. lock.lock();
  68. } finally {
  69. if (lock.isLocked()) {
  70. lock.unlock();
  71. } else {
  72. // 执行超时看门狗释放锁抛异常回滚事务
  73. throw new BusinessException("操作失败请稍后重试");
  74. }
  75. }

十八、Logback 配置

  1. # 遇到一个问题,使用Logback时在logback.xml中使用${spring.application.name}获取配置文件属性时无法获取到,查阅资料后找到解决方案。
  2. 加载顺序logback.xml--->application.properties--->logback-spring.xml,所以需要把logback.xml修改为logback-spring.xml
  3. 在logback-spring.xml中用<springProperty scop="context" name="spring.application.name" source="spring.application.name" defaultValue=""/>这个来获取spring配置文件中的属性
  4. # 日志从高到地低有 OFF 、 FATAL 、 ERROR 、 WARN 、 INFO 、 DEBUG 、 TRACE 、 ALL
  5. 日志输出规则 根据当前ROOT 级别,日志输出时,级别高于root默认的级别时会输出
  6. 属性描述
  7. scan:设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true
  8. scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。
  9. debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false
  10. <configuration scan="true" scanPeriod="60 seconds" debug="false"></configuration>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/469163
推荐阅读
相关标签
  

闽ICP备14008679号