Commit 4e6ca599 authored by 雷明明's avatar 雷明明

多数据源切换 20230302

parent 2d655b1a
......@@ -54,18 +54,34 @@
</dependency>
<!--spring-jdbc的依赖-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-jdbc</artifactId>-->
<!-- </dependency>-->
<!--连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
<version>2.3.12.RELEASE</version>
</dependency>
<!-- mysql驱动 -->
<!--<dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>-->
</dependency>
<!-- sqlite -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.36.0.3</version>
</dependency>
<!-- apache 工具类 -->
<dependency>
......
......@@ -2,8 +2,14 @@ package com.jz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jdbc.repository.config.EnableJdbcAuditing;
import org.springframework.data.jdbc.repository.config.EnableJdbcRepositories;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableJdbcRepositories(basePackages = "com.jz.dao")
@EnableSpringDataWebSupport
@EnableJdbcAuditing(auditorAwareRef = "customAuditorAware")
@SpringBootApplication
@EnableScheduling
public class Application {
......
package com.jz.aspect;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
import java.util.Optional;
/**
* @ClassName:CustomAuditorAware
* @Auther: lei
* @Description:
* @Date: 2023-03-01 14
*
*/
@Component
public class CustomAuditorAware implements AuditorAware<Long> {
@Override
public Optional<Long> getCurrentAuditor() {
//返回登录用户信息 目前固定值
return Optional.of(new Long(1000L));
}
}
package com.jz.aspect;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.ParseException;
import org.apache.http.client.utils.DateUtils;
import org.springframework.util.StringUtils;
import java.beans.PropertyEditorSupport;
import java.util.Date;
/**
* @ClassName:DateEditor
* @Auther: lei
* @Description: 时间解析器
* @Date: 2023-03-01 15
*/
public class DateEditor extends PropertyEditorSupport {
private String pattern[] = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm"
, "yyyy/MM/dd"};
/**
* Parse the Date from the given text, using the lang3 DateUtils.
*/
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text == null || !StringUtils.hasText(text)) {
// Treat empty String as null value.
setValue(null);
} else {
try {
setValue(DateUtils.parseDate(text, pattern));
} catch (ParseException ex) {
throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
}
}
}
/**
* Format the Date as String, using the lang3 Utils.
*/
@Override
public String getAsText() {
Date value = (Date) getValue();
if (value instanceof java.sql.Date) {
return (value != null ? DateFormatUtils.ISO_DATE_FORMAT.format(value) : "");
} else if (value instanceof java.sql.Timestamp) {
return (value != null ? DateFormatUtils.format(value, "yyyy-MM-dd HH:mm:ss") : "");
} else {
return (value != null ? DateFormatUtils.format(value, "yyyy-MM-dd HH:mm:ss") : "");
}
}
}
package com.jz.aspect;
import com.jz.utils.JwtUtil;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//@Component
public class JwtInterceptor implements HandlerInterceptor {
/* Logger logger= Logger.getLogger(JwtInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//如果不是映射到方法直接通过
if (!(handler instanceof HandlerMethod)) {
return true;
}
String uri = request.getRequestURI();
//登陆地址过滤
if (check(uri)) {
return true;
}
//从 http 请求头中取出 token
String token = request.getHeader("token");
if (StringUtils.isEmpty(token)) {
throw new RuntimeException("无 token ,请重新登陆");
}
return JwtUtil.checkSign(token);
}
private boolean check(String uri){
return uri.startsWith("/api/Account/login")||uri.startsWith("/api/Code")|| uri.startsWith("/api/MesSysConfig")||uri.contains("_FILE");
}*/
}
......@@ -14,4 +14,6 @@ public class CrosConfig implements WebMvcConfigurer {
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.maxAge(3600);
}
}
\ No newline at end of file
package com.jz.config;
import com.jz.aspect.JwtInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
/**
* 添加jwt拦截器,并指定拦截路径
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor())
.addPathPatterns("/api/**");
}
/**
* jwt拦截器
*/
@Bean
public JwtInterceptor jwtInterceptor() {
return new JwtInterceptor();
}
}
package com.jz.controller;
import com.jz.aspect.DateEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @ClassName:BaseController
* @Auther: lei
* @Description:
* @Date: 2023-03-01 15
*/
public class BaseController {
@InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Date.class, new DateEditor());
}
}
package com.jz.controller;
import com.jz.common.JSONResult;
import com.jz.entity.UserEntity;
import com.jz.entity.db.DataSourceEntity;
import com.jz.service.UserService;
import com.jz.service.db.DbChangeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
/**
* @ClassName:UserController
......@@ -16,14 +16,61 @@ import org.springframework.web.bind.annotation.RestController;
*/
@RestController
@RequestMapping("/user")
public class UserController {
public class UserController extends BaseController {
private UserService userService;
@Autowired
private DbChangeService dbChangeService;
@GetMapping("/getList")
public JSONResult getList() {
DataSourceEntity dataSourceEntity_sqlite=new DataSourceEntity();
dataSourceEntity_sqlite.setDatasourceId("168-sqlite");
dataSourceEntity_sqlite.setDatabasetype("sqlite");
dataSourceEntity_sqlite.setCode("code");
dataSourceEntity_sqlite.setUrl("jdbc:sqlite:sqlite_db/dbupdate.db");
dbChangeService.changeDb(dataSourceEntity_sqlite);
return JSONResult.ok(userService.getList());
}
@PostMapping("/save")
public JSONResult save(UserEntity userEntity){
DataSourceEntity dataSourceEntity_sqlite=new DataSourceEntity();
dataSourceEntity_sqlite.setDatasourceId("168-sqlite");
dataSourceEntity_sqlite.setDatabasetype("sqlite");
dataSourceEntity_sqlite.setCode("code");
dataSourceEntity_sqlite.setUrl("jdbc:sqlite:sqlite_db/dbupdate.db");
dbChangeService.changeDb(dataSourceEntity_sqlite);
/*userService.getList();*/
userService.save(userEntity);
return JSONResult.ok();
}
@PostMapping("/testDb")
public JSONResult test(){
System.out.println(userService.getList().toString());
/* DataSourceEntity dataSourceEntity=new DataSourceEntity();
dataSourceEntity.setDatasourceId("168-mysql");
dataSourceEntity.setDatabasetype("mysql");
dataSourceEntity.setCode("code");
dataSourceEntity.setUrl("jdbc:mysql://39.100.148.168:3307/system?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC");
dataSourceEntity.setUserName("root");
dataSourceEntity.setPassWord("root@Mysql8@228");
dbChangeService.changeDb(dataSourceEntity);
userService.getList();*/
DataSourceEntity dataSourceEntity_sqlite=new DataSourceEntity();
dataSourceEntity_sqlite.setDatasourceId("168-sqlite");
dataSourceEntity_sqlite.setDatabasetype("sqlite");
dataSourceEntity_sqlite.setCode("code");
dataSourceEntity_sqlite.setUrl("jdbc:sqlite::resource:sqlite/dbupdate.db");
dbChangeService.changeDb(dataSourceEntity_sqlite);
return JSONResult.ok(userService.getList());
}
@Autowired
public void setUserService(UserService userService) {
......
package com.jz.dao.customized;
/**
* @ClassName:userRepository
* @Auther: lei
* @Description:
* @Date: 2023-03-01 10
*/
public interface UserRepository {
}
package com.jz.dao.impl;
package com.jz.dao.customized.impl;
import com.jz.dao.UserDao;
import com.jz.dao.customized.UserRepository;
import com.jz.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @ClassName:UserDaoImpl
* @ClassName:UserRepositoryImpl
* @Auther: lei
* @Description:
* @Date: 2023-02-08 11
* @Date: 2023-03-01 10
*/
@Repository
public class UserDaoImpl implements UserDao {
private JdbcTemplate jdbcTemplate;
@Component
public class UserRepositoryImpl<T> implements UserRepository {
@Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
private JdbcTemplate jdbcTemplate;
/**
* 批量增加
* @param userEntityList
*/
public void batchSave(List<UserEntity> userEntityList){
@Override
public List<UserEntity> getList() {
String sql="select * from SYS_USER";
return jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(UserEntity.class));
}
}
package com.jz.dao;
package com.jz.dao.interfaces;
import com.jz.dao.customized.UserRepository;
import com.jz.entity.UserEntity;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.Repository;
import java.util.List;
......@@ -10,8 +13,6 @@ import java.util.List;
* @Description:
* @Date: 2023-02-08 11
*/
public interface UserDao {
List<UserEntity> getList();
public interface UserDao extends PagingAndSortingRepository<UserEntity,Long>, UserRepository {
}
package com.jz.db.handle;
import org.apache.log4j.Logger;
public class DataSourceKeyHolder {
static Logger log= Logger.getLogger(DataSourceKeyHolder.class);
private static ThreadLocal<String> threadLocal = new ThreadLocal<>();
public static String getDataSource() {
return threadLocal.get();
}
public static void set(String key) {
threadLocal.set(key);
}
// 删除数据源
public static void clearDataSource() {
threadLocal.remove();
}
}
This diff is collapsed.
package com.jz.db.handle;
import com.alibaba.druid.pool.DruidDataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableTransactionManagement
public class JdbcTemplateConfiguration {
@Value("${spring.datasource.url}")
private String dbUrl;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driverClassName;
// 连接池连接信息
@Value("${spring.datasource.druid.initial-size}")
private int initialSize;
@Value("${spring.datasource.druid.min-idle}")
private int minIdle;
@Value("${spring.datasource.druid.max-active}")
private int maxActive;
@Value("${spring.datasource.druid.max-wait}")
private int maxWait;
// 第一个数据源的相关配置
@Bean // 声明其为Bean实例
@Primary // 在同样的DataSource中,首先使用被标注的DataSource
@Qualifier("mainDataSource")
public DataSource mainDataSource() {
//HikariDataSource datasource=new HikariDataSource();
DruidDataSource datasource = new DruidDataSource();
// 基础连接信息
datasource.setUrl(dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
// 连接池连接信息
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setPoolPreparedStatements(true); //是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。
datasource.setMaxPoolPreparedStatementPerConnectionSize(20);
// datasource.setConnectionProperties("oracle.net.CONNECT_TIMEOUT=6000;oracle.jdbc.ReadTimeout=60000");//对于耗时长的查询sql,会受限于ReadTimeout的控制,单位毫秒
datasource.setConnectionProperties("druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000");//对于耗时长的查询sql,会受限于ReadTimeout的控制,单位毫秒
datasource.setTestOnBorrow(true); //申请连接时执行validationQuery检测连接是否有效,这里建议配置为TRUE,防止取到的连接不可用
datasource.setTestWhileIdle(true);//建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
String validationQuery = "select 1 ";
datasource.setValidationQuery(validationQuery); //用来检测连接是否有效的sql,要求是一个查询语句。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。
try {
datasource.setFilters("stat,slf4j");//属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:监控统计用的filter:stat日志用的filter:log4j防御sql注入的filter:wall
} catch (SQLException throwables) {
throwables.printStackTrace();
}
datasource.setTimeBetweenEvictionRunsMillis(60000); //配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
datasource.setMinEvictableIdleTimeMillis(180000); //配置一个连接在池中最小生存的时间,单位是毫秒,这里配置为3分钟180000
datasource.setKeepAlive(true); //打开druid.keepAlive之后,当连接池空闲时,池中的minIdle数量以内的连接,空闲时间超过minEvictableIdleTimeMillis,则会执行keepAlive操作,即执行druid.validationQuery指定的查询SQL,一般为select * from dual,只要minEvictableIdleTimeMillis设置的小于防火墙切断连接时间,就可以保证当连接空闲时自动做保活检测,不会被防火墙切断
datasource.setRemoveAbandoned(true); //是否移除泄露的连接/超过时间限制是否回收。
datasource.setRemoveAbandonedTimeout(3600); //泄露连接的定义时间(要超过最大事务的处理时间);单位为秒。这里配置为1小时
datasource.setLogAbandoned(true); //移除泄露连接发生是是否记录日志
return datasource;
}
@Bean(name = "dynamicDataSource")
@Qualifier("dynamicDataSource")
public DynamicDataSource dynamicDataSource() {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
//dynamicDataSource.setDebug(false);
//配置缺省的数据源
Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
//额外数据源配置 TargetDataSources
targetDataSources.put("mainDataSource", mainDataSource());
dynamicDataSource.setTargetDataSources(targetDataSources);
// 默认数据源配置 DefaultTargetDataSource
dynamicDataSource.setDefaultTargetDataSource(mainDataSource());
return dynamicDataSource;
}
@Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dynamicDataSource());
}
/* @Bean
public TransactionManager transactionManager() {
PlatformTransactionManager transactionManager = new DataSourceTransactionManager(DynamicDataSource());
return transactionManager;
}*/
@Bean
public DataSourceTransactionManager transactionManager(DynamicDataSource dynamicDataSource) {
DataSourceTransactionManager manager= new DataSourceTransactionManager(dynamicDataSource);
return manager;
}
}
package com.jz.entity;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.relational.core.mapping.Column;
import java.io.Serializable;
import java.util.Date;
/**
* @ClassName:BaseEntity
* @Auther: lei
* @Description: superEntity
* @Date: 2023-03-01 14
*/
public class BaseEntity implements Serializable {
/**
* 创建日期
*/
@CreatedDate
@Column(value = "create_date")
private String createDate;
/**
* 更新日期
*/
@LastModifiedDate
@Column(value = "update_date")
private String updateDate;
/**
* 创建人
*/
@CreatedBy
@Column(value = "create_id")
private Long createId;
/**
* 更新人
*/
@LastModifiedBy
@Column(value = "update_id")
private Long updateId;
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
public String getUpdateDate() {
return updateDate;
}
public void setUpdateDate(String updateDate) {
this.updateDate = updateDate;
}
public Long getCreateId() {
return createId;
}
public void setCreateId(Long createId) {
this.createId = createId;
}
public Long getUpdateId() {
return updateId;
}
public void setUpdateId(Long updateId) {
this.updateId = updateId;
}
}
package com.jz.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.domain.Persistable;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
import java.io.Serializable;
import java.util.Date;
......@@ -9,131 +14,173 @@ import java.util.Date;
* @Description:
* @Date: 2023-02-08 11
*/
public class UserEntity implements Serializable {
private Long ID;
@Table(value="zy_account")
public class UserEntity extends BaseEntity {
/**
* 用户名
* 主键Id
*/
private String USER_NAME;
@Id
private Long id;
/**
* 用户编号
* 用户
*/
private String CARDNO;
@Column(value = "user_name")
private String userName;
/**
* 密码
*/
private String PASSWORD;
private String password;
/**
* 状态
* 姓名
*/
private Integer STATUS;
private String name;
/**
* 用户类型
*/
private Integer USER_TYPE;
private Short type;
/**
* 备注
* 状态
*/
private String NOTE;
private String status;
/**
* 创建时间
* 软删除
*/
private Date CREATE_DATE;
@Column(value = "is_delete")
private Long isDelete;
/**
* 手机
* 获取主键Id
*
* @return id - 主键Id
*/
private String PHONE;
private String USERNAME;
public Long getID() {
return ID;
public Long getId() {
return id;
}
public void setID(Long ID) {
this.ID = ID;
}
public String getUSER_NAME() {
return USER_NAME;
}
public void setUSER_NAME(String USER_NAME) {
this.USER_NAME = USER_NAME;
}
public String getCARDNO() {
return CARDNO;
}
public void setCARDNO(String CARDNO) {
this.CARDNO = CARDNO;
}
public String getPASSWORD() {
return PASSWORD;
/**
* 设置主键Id
*
* @param id 主键Id
*/
public void setId(Long id) {
this.id = id;
}
public void setPASSWORD(String PASSWORD) {
this.PASSWORD = PASSWORD;
/**
* 获取用户名
*
* @return user_name - 用户名
*/
public String getUserName() {
return userName;
}
public Integer getSTATUS() {
return STATUS;
/**
* 设置用户名
*
* @param userName 用户名
*/
public void setUserName(String userName) {
this.userName = userName;
}
public void setSTATUS(Integer STATUS) {
this.STATUS = STATUS;
/**
* 获取密码
*
* @return password - 密码
*/
public String getPassword() {
return password;
}
public Integer getUSER_TYPE() {
return USER_TYPE;
/**
* 设置密码
*
* @param password 密码
*/
public void setPassword(String password) {
this.password = password;
}
public void setUSER_TYPE(Integer USER_TYPE) {
this.USER_TYPE = USER_TYPE;
/**
* 获取姓名
*
* @return name - 姓名
*/
public String getName() {
return name;
}
public String getNOTE() {
return NOTE;
/**
* 设置姓名
*
* @param name 姓名
*/
public void setName(String name) {
this.name = name;
}
public void setNOTE(String NOTE) {
this.NOTE = NOTE;
/**
* 获取用户类型
*
* @return type - 用户类型
*/
public Short getType() {
return type;
}
public Date getCREATE_DATE() {
return CREATE_DATE;
/**
* 设置用户类型
*
* @param type 用户类型
*/
public void setType(Short type) {
this.type = type;
}
public void setCREATE_DATE(Date CREATE_DATE) {
this.CREATE_DATE = CREATE_DATE;
/**
* 获取状态
*
* @return status - 状态
*/
public String getStatus() {
return status;
}
public String getPHONE() {
return PHONE;
/**
* 设置状态
*
* @param status 状态
*/
public void setStatus(String status) {
this.status = status;
}
public void setPHONE(String PHONE) {
this.PHONE = PHONE;
}
public String getUSERNAME() {
return USERNAME;
/**
* 获取软删除
*
* @return is_delete - 软删除
*/
public Long getIsDelete() {
return isDelete;
}
public void setUSERNAME(String USERNAME) {
this.USERNAME = USERNAME;
/**
* 设置软删除
*
* @param isDelete 软删除
*/
public void setIsDelete(Long isDelete) {
this.isDelete = isDelete;
}
}
package com.jz.entity.db;
public class DataSourceEntity {
Integer id;
String datasourceId;
String url;
String userName;
String passWord;
String code;
String databasetype;
String sql;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public String getDatasourceId() {
return datasourceId;
}
public void setDatasourceId(String datasourceId) {
this.datasourceId = datasourceId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDatabasetype() {
return databasetype;
}
public void setDatabasetype(String databasetype) {
this.databasetype = databasetype;
}
}
......@@ -13,4 +13,5 @@ import java.util.List;
public interface UserService {
List<UserEntity> getList();
void save(UserEntity userEntity);
}
package com.jz.service.db;
import com.jz.db.handle.DataSourceKeyHolder;
import com.jz.db.handle.DynamicDataSource;
import com.jz.entity.db.DataSourceEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("dbChangeService")
public class DbChangeService{
Logger logger= LoggerFactory.getLogger(DbChangeService.class);
@Autowired
private DynamicDataSource dynamicDataSource;
public boolean changeDb(DataSourceEntity dataSourceEntity) {
//清除本地局部变量
DataSourceKeyHolder.clearDataSource();
try {
dynamicDataSource.createDataSourceWithCheck(dataSourceEntity);
DataSourceKeyHolder.set(dataSourceEntity.getDatasourceId());
} catch (Exception e) {
logger.error("数据源切换失败!!!");
e.printStackTrace();
}
return false;
}
}
package com.jz.service.impl;
import com.jz.dao.UserDao;
import com.jz.dao.interfaces.UserDao;
import com.jz.entity.UserEntity;
import com.jz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -16,19 +16,26 @@ import java.util.List;
*/
@Service
public class UserServiceImpl implements UserService {
private UserDao userDao;
@Autowired
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
private UserDao userDao;
/**
*
* @return
*/
public List<UserEntity> getList(){
return userDao.getList();
return (List<UserEntity>) userDao.findAll();
}
@Override
public void save(UserEntity userEntity) {
userDao.save(userEntity);
}
@Autowired
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
......@@ -22,29 +22,23 @@ spring:
url: jdbc:oscar://${DB_HOST:192.168.0.180}:2003/OSRDB?serverTimezone=UTC&useSSL=FALSE
username: ${DB_USERNAME:HYHMES}
password: ${DB_PASSWORD:admin}
hikari:
connection-timeout: 30000 # 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 默认:30秒
minimum-idle: 5 # 最小连接数
maximum-pool-size: 20 # 最大连接数
auto-commit: true # 自动提交
idle-timeout: 600000 # 连接超时的最大时长(毫秒),超时则被释放(retired),默认:10分钟
pool-name: DateSourceHikariCP # 连接池名字
max-lifetime: 1800000 # 连接的生命时长(毫秒),超时而且没被使用则被释放(retired),默认:30分钟 1800000ms
connection-test-query: SELECT 1
#json文件传输地址配置
my-json-file:
status:
order: true #是否开启order执行程序
special-page: true #是否开启special-page执行程序
user: true #是否开启user执行程序
path:
order: D:\jsonFile\orderData\
order-file: D:\jsonFile\fileData\
special-page: D:\jsonFile\specialPage\
user: D:\jsonFile\userData\
export-path:
execute: D:\jsonExport\executeData\
result: D:\jsonExport\resultData\
module: D:\jsonExport\moduleFileData\
user: D:\jsonExport\personnelData\
\ No newline at end of file
druid:
initial-size: 2
min-idle: 2
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000 #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
min-evictable-idle-time-millis: 300000 #配置一个连接在池中最小生存的时间,单位是毫秒
validationQuery: SELECT 1
testWhileIdle: true
testOnBorrow: true
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,slf4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
\ No newline at end of file
......@@ -17,35 +17,31 @@ server:
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.oscar.Driver
url: jdbc:oscar://${DB_HOST:localhost}:2003/OSRDB?serverTimezone=UTC&useSSL=FALSE
username: ${DB_USERNAME:HYHMES}
password: ${DB_PASSWORD:admin}
hikari:
connection-timeout: 30000 # 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 默认:30秒
minimum-idle: 5 # 最小连接数
maximum-pool-size: 20 # 最大连接数
auto-commit: true # 自动提交
idle-timeout: 600000 # 连接超时的最大时长(毫秒),超时则被释放(retired),默认:10分钟
pool-name: DateSourceHikariCP # 连接池名字
max-lifetime: 1800000 # 连接的生命时长(毫秒),超时而且没被使用则被释放(retired),默认:30分钟 1800000ms
connection-test-query: SELECT 1
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
#url: jdbc:oscar://${DB_HOST:localhost}:2003/OSRDB?serverTimezone=UTC&useSSL=FALSE
url: jdbc:mysql://${DB_HOST:192.168.0.180}:3366/dbupdate?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
username: ${DB_USERNAME:root}
password: ${DB_PASSWORD:root_mes@123456~}
druid:
initial-size: 2
min-idle: 2
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000 #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
min-evictable-idle-time-millis: 300000 #配置一个连接在池中最小生存的时间,单位是毫秒
validationQuery: SELECT 1
testWhileIdle: true
testOnBorrow: true
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: false
maxPoolPreparedStatementPerConnectionSize: -1
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,slf4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
#json文件传输地址配置
my-json-file:
status:
order: true #是否开启order执行程序
special-page: true #是否开启special-page执行程序
user: true #是否开启user执行程序
path:
order: D:\jsonFile\orderData\
order-file: D:\jsonFile\fileData\
special-page: D:\jsonFile\specialPage\
user: D:\jsonFile\userData\
export-path:
execute: D:\jsonExport\executeData\
result: D:\jsonExport\resultData\
module: D:\jsonExport\moduleFileData\
user: D:\jsonExport\personnelData\
\ No newline at end of file
......@@ -22,30 +22,26 @@ spring:
url: jdbc:oscar://${DB_HOST:10.83.100.150}:2003/OSRDB?serverTimezone=UTC&useSSL=FALSE
username: ${DB_USERNAME:SYSDBA}
password: ${DB_PASSWORD:szoscar55}
hikari:
connection-timeout: 30000 # 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 默认:30秒
minimum-idle: 5 # 最小连接数
maximum-pool-size: 20 # 最大连接数
auto-commit: true # 自动提交
idle-timeout: 600000 # 连接超时的最大时长(毫秒),超时则被释放(retired),默认:10分钟
pool-name: DateSourceHikariCP # 连接池名字
max-lifetime: 1800000 # 连接的生命时长(毫秒),超时而且没被使用则被释放(retired),默认:30分钟 1800000ms
connection-test-query: SELECT 1
druid:
initial-size: 2
min-idle: 2
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000 #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
min-evictable-idle-time-millis: 300000 #配置一个连接在池中最小生存的时间,单位是毫秒
validationQuery: SELECT 1
testWhileIdle: true
testOnBorrow: true
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,slf4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
#json文件传输地址配置
my-json-file:
status:
order: true #是否开启order执行程序
special-page: true #是否开启special-page执行程序
user: true #是否开启user执行程序
path:
order: /usr/local/jsonFile/orderData/
order-file: /usr/local/jsonFile/fileData/
special-page: /usr/local/jsonFile/specialPage/
user: /usr/local/jsonFile/userData/
export-path:
execute: /usr/local/jsonExport/executeData/
result: /usr/local/jsonExport/resultData/
module: /usr/local/jsonExport/moduleFileData/
user: /usr/local/jsonExport/personnelData/
......@@ -22,29 +22,24 @@ spring:
url: jdbc:oscar://${DB_HOST:47.92.102.113}:2003/OSRDB?serverTimezone=UTC&useSSL=FALSE
username: ${DB_USERNAME:HYHMES}
password: ${DB_PASSWORD:admin}
hikari:
connection-timeout: 30000 # 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 默认:30秒
minimum-idle: 5 # 最小连接数
maximum-pool-size: 20 # 最大连接数
auto-commit: true # 自动提交
idle-timeout: 600000 # 连接超时的最大时长(毫秒),超时则被释放(retired),默认:10分钟
pool-name: DateSourceHikariCP # 连接池名字
max-lifetime: 1800000 # 连接的生命时长(毫秒),超时而且没被使用则被释放(retired),默认:30分钟 1800000ms
connection-test-query: SELECT 1
druid:
initial-size: 2
min-idle: 2
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000 #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
min-evictable-idle-time-millis: 300000 #配置一个连接在池中最小生存的时间,单位是毫秒
validationQuery: SELECT 1
testWhileIdle: true
testOnBorrow: true
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,slf4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
#json文件传输地址配置
my-json-file:
status:
order: true #是否开启order执行程序
special-page: true #是否开启special-page执行程序
user: true #是否开启user执行程序
path:
order: E:\jsonFile\orderData\
order-file: E:\jsonFile\fileData\
special-page: E:\jsonFile\specialPage\
user: E:\jsonFile\userData\
export-path:
execute: E:\jsonExport\executeData\
result: E:\jsonExport\resultData\
module: E:\jsonExport\moduleFileData\
user: E:\jsonExport\personnelData\
\ No newline at end of file
spring:
# 环境 dev:开发环境|test:测试环境|prod:生产环境
profiles:
# active: pro #产品环境的配置文件
active: dev #180数据库 的配置
# active: local #本地的配置
# active: test #113测试环境配置文件
servlet:
multipart:
# 环境 dev:开发环境|test:测试环境|prod:生产环境
profiles:
#active: pro #产品环境的配置文件
#active: dev #180数据库 的配置
active: local #本地的配置
#active: test #113测试环境配置文件
servlet:
multipart:
enabled: true
max-file-size: 100MB
max-request-size: 100MB
jackson:
# 格式化返回时间 yyyy-MM-dd HH:mm:ss
date-format: yyyy-MM-dd HH:mm:ss
# 设置时区
time-zone: GMT+8
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment