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層封裝
封裝的一些配置
application.yml
banner: charset: UTF-8 location: classpath:banner.txtserver: port: 5555 contextPath: / session: timeout: 0spring: 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.0spring-boot-datasource-demospring-boot-datasource-demo0.0.1-SNAPSHOTspring-boot-datasource-demospring-boot-datasource-demoorg.springframework.bootspring-boot-starter-parent1.4.1.RELEASEUTF-8UTF-81.83.3.22.7.0org.springframework.bootspring-boot-starterorg.springframework.bootspring-boot-starter-data-mongodborg.springframework.bootspring-boot-starter-data-elasticsearchorg.springframework.bootspring-boot-starter-data-jpamysqlmysql-connector-javaruntimeorg.springframework.bootspring-boot-starter-webio.springfoxspringfox-swagger2${springfox.version}io.springfoxspringfox-swagger-ui${springfox.version}com.alibabafastjson1.2.15org.apache.commonscommons-lang3${commons.lang.version}org.apache.commonscommons-collections44.1com.github.wenhaojpa-spec3.2.3srcmaven-compiler-plugin1.81.8
封裝後使用
封裝之後使用将非常簡單,公共的Service行為将被封裝處理
¶MySQL 動态資料通路
通過幾行代碼即可實作對MySQL的通路,同時支援動态的條件查詢;
User* Dao
@Repositorypublic interface IUserDao extends IBaseJpaDao{}
Service
public interface IUserService extends IBaseJpaService {}@Servicepublic 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
@[email protected]("/admin/user")public class UserController { @Autowired private IUserService userService; @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
@Repositorypublic interface IEventRuleDao extends IBaseMongoDao {}
Service
public interface IEventRuleService extends IBaseMongoService {}@Servicepublic class EventRuleServiceImpl extends BaseMongoServiceImpl implements IEventRuleService { @Autowired IEventRuleDao eventRuleDao; @Override public IBaseMongoDao getBaseDao() { return eventRuleDao; }}
Controller
@[email protected]("/admin/eventRule")public class EventRuleController { @Autowired private IEventRuleService eventRuleService; @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
@Repositorypublic interface ISysLogDao extends IBaseESDao {}
Service
public interface ILogService extends IBaseESService {}@Servicepublic class LogServiceImpl extends BaseESServiceImpl implements ILogService { @Autowired ISysLogDao sysLogDao; @Override public IBaseESDao getBaseDao() { return sysLogDao; }}
Controller
@[email protected]("/admin/log")public class LogController { @Autowired private ILogService logService; @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 {}@Repositorypublic class DymLogDaoImpl extends SimpleDynamicEsDaoImpl implements IDymLogDao { @Autowired protected ElasticsearchTemplate elasticsearchTemplate; @Override public ElasticsearchOperations getElasticsearchOperations() { return elasticsearchTemplate; }}
Service
public interface IDymLogService extends IDynamicESService {}@Servicepublic class DymLogServiceImpl extends DynamicESServiceImpl implements IDymLogService { @Autowired IDymLogDao sysLogDao; @Override public IDynamicEsDao getBaseDao() { return sysLogDao; }}
Controller
@[email protected]("/admin/dymLog")public class DymLogController { @Autowired private IDymLogService logService; @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()); }}
源代碼托管