Spring Boot骚操作-多数据源Service层封装

原文:https://www.pdai.tech/md/spring/springboot-data-multi.html

mysql, es, mongodb 三个数据源用配置文件方式连接,JPA只是正对dao做了封装,本文主要介绍如何对service层进行封装。

  • Spring Boot - 多个数据源Service层封装

  • 类关系图

  • 封装的一些配置

    • application.yml

    • pom.xml

  • 封装后使用

    • MySQL 动态数据访问

  • Mongo 动态数据访问

  • ElasticSearch 动态数据访问(单个index+type)

  • ElasticSearch 动态数据访问(多个index+type)

  • 源代码托管

类关系图

  • 对多个数据源连接获取数据进行统一封装

  • ES spring-data方式不支持多个Index和Type的查找功能,添加了DynamicESDao支持

  • 大大简化封装之后的调用, 调用方式如下

Spring Boot骚操作-多数据源Service层封装_第1张图片

封装的一些配置

application.yml

banner:
  charset: UTF-8
  location: classpath:banner.txt
server:
  port: 5555
  contextPath: /
  session:
    timeout: 0
spring:
  application:
    name: 'spring-boot-datasource-demo'
  output:
    ansi:
      enabled: DETECT
  messages:
    basename: i18n/messages
  thymeleaf:
    cache: false
  profiles:
    active: dev
  # MySQL data source settings
  datasource:
    url: jdbc:mysql://localhost:3306/cdc_standalone?useSSL=false
    username: root
    password: bfXa4Pt2lUUScy8jakXf
  # MySQL JPA settings
  jpa:
    generate-ddl: true
    show-sql: true
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQLDialect
        format_sql: true
  # NoSQL data source settings
  data:
    # MongoDB 2.2+ settings
    mongodb:
      uri: mongodb://standalone:[email protected]:27017/standalone
    # ElasticSearch settings
    elasticsearch:
      cluster-name: es-logs-01
      cluster-nodes: 10.11.60.5:9300

pom.xml


    4.0.0
    spring-boot-datasource-demo
    spring-boot-datasource-demo
    0.0.1-SNAPSHOT
    spring-boot-datasource-demo
    spring-boot-datasource-demo
    
        org.springframework.boot
        spring-boot-starter-parent
        1.4.1.RELEASE
    
    
        UTF-8
        UTF-8
        1.8
        3.3.2
        2.7.0
    
    
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-data-mongodb
        
        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            io.springfox
            springfox-swagger2
            ${springfox.version}
        
        
            io.springfox
            springfox-swagger-ui
            ${springfox.version}
        
        
            com.alibaba
            fastjson
            1.2.15
        
        
            org.apache.commons
            commons-lang3
            ${commons.lang.version}
        
        
            org.apache.commons
            commons-collections4
            4.1
        
        
            com.github.wenhao
            jpa-spec
            3.2.3
        
    
    
        src
        
            
                maven-compiler-plugin
                
                    1.8
                    1.8
                
            
        
    

封装后使用

封装之后使用将非常简单,公共的Service行为将被封装处理

MySQL 动态数据访问

通过几行代码即可实现对MySQL的访问,同时支持动态的条件查询;

  • User

@Entity
@Table(name = "tb_user")
public class User extends BaseEntity {
    private static final long serialVersionUID = 1L;
    /**
     * 用户id
     */
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false)
    private Integer id;
    private String userName;
    private String nickName;
    private String password;
    private Integer sex;
    private String telephone;
    private String email;
    private String address;
    private Integer deleteStatus;
    private Integer locked = 0;
    private String description;
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;
    @JSONField(format = "yyyy-MM-dd HH:mm:ss")
    private Date updateTime;
    @ManyToMany(cascade = { CascadeType.REFRESH }, fetch = FetchType.LAZY)
    @JoinTable(name = "tb_user_role", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = {
            @JoinColumn(name = "role_id") })
    private java.util.Set roles;
    // getter & setter
}
  • Dao

@Repository
public interface IUserDao extends IBaseJpaDao{
}
  • Service

public interface IUserService extends IBaseJpaService {
}
@Service
public class UserServiceImpl extends BaseJpaServiceImpl implements IUserService {
    @Autowired
    private IUserDao userDao;
    @Override
    public IBaseJpaDao getBaseDao() {
        return this.userDao;
    }
    @Override
    public void delete(Integer id) {
        User user = find(id);
        Assert.state(!"admin".equals(user.getUserName()), "超级管理员用户不能删除");
        super.delete(id);
    }
}
  • Controller

@RestController
@RequestMapping("/admin/user")
public class UserController {
    /**
     * user service
     */
    @Autowired
    private IUserService userService;
    /**
     * @param searchText
     * @param user
     * @param model
     * @return
     */
    @GetMapping(value = "/list")
    public List list(@RequestParam(value = "searchText", required = false, defaultValue="a") String searchText) {
        return userService.findAll(Specifications.and().like("userName", "%" + searchText + "%").build());
    }
}

Mongo 动态数据访问

通过几行代码即可实现对Mongo的访问,同时支持动态的条件查询;

  • Entity

@Document(collection = "security_alert_rules")
public class EventRule extends BaseEntity {
    private static final long serialVersionUID = -2013673868028645757L;
    public static final int EVENT_STATUS_ENABLE = 0, EVENT_STATUS_DISABLE = 1;
    private String component;
    private String name;
    private String eventId;
    private String ciaLevel;
    private String remarks;
    private String script;
    private long threshold;
    private long timeWindow;
    private String parseEsResultKeys;
    private String nameCN;
    private String remarkCN;
    private String ruleType;
    private String redisEventKey;
    private int status = EVENT_STATUS_ENABLE;
    // getter & setter
}
  • Dao

@Repository
public interface IEventRuleDao extends IBaseMongoDao {
}
  • Service

public interface IEventRuleService extends IBaseMongoService {
}
@Service
public class EventRuleServiceImpl extends BaseMongoServiceImpl implements IEventRuleService {
    @Autowired
    IEventRuleDao eventRuleDao;
    @Override
    public IBaseMongoDao getBaseDao() {
        return eventRuleDao;
    }
}
  • Controller

@RestController
@RequestMapping("/admin/eventRule")
public class EventRuleController {
    /**
     */
    @Autowired
    private IEventRuleService eventRuleService;
    /**
     * @param searchText
     * @param user
     * @param model
     * @return
     */
    @GetMapping(value = "/list")
    public List list(@RequestParam(value = "searchText", required = false) String searchText) {
        EventRule param = new EventRule();
        param.setName(searchText);
//        Example rule = Example.of(param,
//                ExampleMatcher.matching().withMatcher("name", ExampleMatcher.GenericPropertyMatchers.exact()));
        Example rule = Example.of(param, ExampleMatcher.matching().withIgnoreCase("name","nameCN"));
        return eventRuleService.findAll(rule);
    }
}

ElasticSearch 动态数据访问(单个index+type)

通过几行代码即可实现对ElasticSearch的访问,同时支持动态的条件查询;适合数据类型比较固定,且index和type独立的,比如强类型映射的实体类;

  • Entity

@Document(indexName="syslog", type="logs")
public class SysLog extends BaseEntity {
    private static final long serialVersionUID = -4491916941883088972L;
    @Id
    private String _id;
    private Set phyPorts = new LinkedHashSet<>();
    private Set ports = new LinkedHashSet<>();
    private String sensor;
    private int vlan;
    private Set ip = new LinkedHashSet<>();
    private Set mac = new LinkedHashSet<>();
    private String description;
    private String type;
    private String vendor;
    private long timestamp;
    private String name;
    private String chassisId;
    // getter & setter
}
  • Dao

@Repository
public interface ISysLogDao extends IBaseESDao {
}
  • Service

public interface ILogService extends IBaseESService {
}
@Service
public class LogServiceImpl extends BaseESServiceImpl implements ILogService {
    @Autowired
    ISysLogDao sysLogDao;
    @Override
    public IBaseESDao getBaseDao() {
        return sysLogDao;
    }
}
  • Controller

@RestController
@RequestMapping("/admin/log")
public class LogController {
    /**
     * user service
     */
    @Autowired
    private ILogService logService;
    /**
     * @param searchText
     * @param user
     * @param model
     * @return
     */
    @GetMapping(value = "/list")
    public Page list(@RequestParam(value = "searchText", required = false) String searchText) {
        return logService.search(QueryBuilders.matchQuery("_all", searchText), new PageRequest(0, 100));
    }
}

ElasticSearch 动态数据访问(多个index+type)

通过几行代码即可实现对ElasticSearch的访问,同时支持动态的条件查询;适合数据类型不固定,且index和type有多个,这些index具备相同结构类型,比如syslog-EVERY-DATE(由于日志量大,将每天的日志单独存放在一个Index中);

  • Entity

@Document(indexName="syslog", type="logs")
public class SysLog extends BaseEntity {
    private static final long serialVersionUID = -4491916941883088972L;
    @Id
    private String _id;
    private Set phyPorts = new LinkedHashSet<>();
    private Set ports = new LinkedHashSet<>();
    private String sensor;
    private int vlan;
    private Set ip = new LinkedHashSet<>();
    private Set mac = new LinkedHashSet<>();
    private String description;
    private String type;
    private String vendor;
    private long timestamp;
    private String name;
    private String chassisId;
    // getter & setter
}
  • Dao

public interface IDymLogDao extends IDynamicEsDao {
}
@Repository
public class DymLogDaoImpl extends SimpleDynamicEsDaoImpl implements IDymLogDao {
    @Autowired
    protected ElasticsearchTemplate elasticsearchTemplate;
    @Override
    public ElasticsearchOperations getElasticsearchOperations() {
        return elasticsearchTemplate;
    }
}
  • Service

public interface IDymLogService extends IDynamicESService {
}
@Service
public class DymLogServiceImpl extends DynamicESServiceImpl implements IDymLogService {
    @Autowired
    IDymLogDao sysLogDao;
    @Override
    public IDynamicEsDao getBaseDao() {
        return sysLogDao;
    }
}
  • Controller

@RestController
@RequestMapping("/admin/dymLog")
public class DymLogController {
    /**
     * logService
     */
    @Autowired
    private IDymLogService logService;
    /**
     * @param searchText
     * @param user
     * @param model
     * @return
     */
    @GetMapping(value = "/list")
    public Page list(
            @RequestParam(value = "searchText", required = false, defaultValue = "Siemens") String searchText) {
        QueryBuilder queryBuilder = QueryBuilders.matchQuery("vendor", searchText);
        return logService.search(new NativeSearchQueryBuilder().withIndices("syslog-2018-12-17").withTypes("logs")
                .withQuery(queryBuilder).build());
    }
}

源代码托管

https://github.com/realpdai/springboot-data-multidatasource-demo

热门内容:

  • 一招搞定GitHub下载加速!

  • Java项目构建基础:统一结果,统一异常,统一日志(好文推荐)

  • Kafka为什么这么快?

  • 一线大厂的分布式唯一ID生成方案是什么样的?

  • JVM 史上最最最完整深入解析(12000 字噢)

  • 硬货 | Redis 性能问题分析

  • Spring Boot 服务监控,健康检查,线程信息,JVM堆信息,指标收集,运行情况监控等!

Spring Boot骚操作-多数据源Service层封装_第2张图片

最近面试BAT,整理一份面试资料《Java面试BAT通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。

获取方式:点“在看”,关注公众号并回复 666 领取,更多内容陆续奉上。

明天见(。・ω・。

你可能感兴趣的:(数据库,分布式,java,maven,spring,boot)