IdentifierGeneratorAutoConfiguration.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Copyright (c) 2011-2021, baomidou (jobob@qq.com).
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.baomidou.mybatisplus.autoconfigure;
  17. import com.baomidou.mybatisplus.core.config.GlobalConfig;
  18. import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
  19. import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
  20. import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
  21. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  22. import org.springframework.cloud.commons.util.InetUtils;
  23. import org.springframework.context.annotation.Bean;
  24. import org.springframework.context.annotation.Configuration;
  25. /**
  26. * @author nieqiurong 2021/1/29
  27. * @since 3.4.3
  28. */
  29. @Configuration
  30. @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
  31. public class IdentifierGeneratorAutoConfiguration {
  32. @Configuration
  33. @ConditionalOnClass(InetUtils.class)
  34. public static class InetUtilsAutoConfig {
  35. private final InetUtils inetUtils;
  36. private final MybatisPlusProperties properties;
  37. public InetUtilsAutoConfig(InetUtils inetUtils, MybatisPlusProperties properties) {
  38. this.inetUtils = inetUtils;
  39. this.properties = properties;
  40. }
  41. @Bean
  42. @ConditionalOnMissingBean
  43. public IdentifierGenerator identifierGenerator() {
  44. GlobalConfig globalConfig = properties.getGlobalConfig();
  45. Long workerId = globalConfig.getWorkerId();
  46. Long datacenterId = globalConfig.getDatacenterId();
  47. if (workerId != null && datacenterId != null) {
  48. return new DefaultIdentifierGenerator(workerId, datacenterId);
  49. } else {
  50. return new DefaultIdentifierGenerator(inetUtils.findFirstNonLoopbackAddress());
  51. }
  52. }
  53. }
  54. }