前言
Druid是阿里巴巴开源的数据库连接池,号称是Java语言中最好的数据库连接池,能够提供强大的监控和扩展功能。GitHub地址:https://github.com/alibaba/druid。
1、pom.xml文件
添加jpa、mysql和druid依赖。
<properties>
<java.version>1.8</java.version>
<druid.version>1.1.16</druid.version>
</properties>
<dependencies>
<!--jpa-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
</dependencies>
2、配置文件
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 初始化大小,最小,最大
initialSize: 5
minIdle: 5
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
# Oracle请使用select 1 from dual
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: true
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,slf4j
maxPoolPreparedStatementPerConnectionSize: 20
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
jpa:
#配置 DBMS 类型
database: MYSQL
show-sql: true
properties:
hibernate:
hbm2ddl:
auto: update
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
3、Druid配置类
@Configuration
public class DruidConfig {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@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.initialSize}")
private int initialSize;
@Value("${spring.datasource.minIdle}")
private int minIdle;
@Value("${spring.datasource.maxActive}")
private int maxActive;
@Value("${spring.datasource.maxWait}")
private int maxWait;
@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.validationQuery}")
private String validationQuery;
@Value("${spring.datasource.testWhileIdle}")
private boolean testWhileIdle;
@Value("${spring.datasource.testOnBorrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.testOnReturn}")
private boolean testOnReturn;
@Value("${spring.datasource.poolPreparedStatements}")
private boolean poolPreparedStatements;
@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize;
@Value("${spring.datasource.filters}")
private String filters;
@Value("{spring.datasource.connectionProperties}")
private String connectionProperties;
@Bean
@Primary //主数据源
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
logger.info("----------- druid datasource ----------");
datasource.setUrl(this.dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
//configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
logger.error("druid configuration Exception", e);
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
/**
* 自定义的Servlet注册
*
* @return
*/
@Bean
public ServletRegistrationBean statViewServlet() {
// 创建servlet注册实体
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet());
//druid监控统计路径
servletRegistrationBean.addUrlMappings("/druid/*");
// 设置ip白名单(没有配置或者为空,则允许所有访问)
servletRegistrationBean.addInitParameter("allow", "");
// 设置ip黑名单,如果allow与deny共同存在时,deny优先于allow
servletRegistrationBean.addInitParameter("deny", "");
// 设置控制台管理用户
servletRegistrationBean.addInitParameter("loginUsername", "admin");
servletRegistrationBean.addInitParameter("loginPassword", "admin");
// 是否可以重置数据
servletRegistrationBean.addInitParameter("resetEnable", "false");
return servletRegistrationBean;
}
/**
* 自定义的Filter注册
* @return
*/
@Bean
public FilterRegistrationBean statFilter() {
// 创建过滤器
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
// filterRegistrationBean.setName("druidWebStatFilter");
// 设置过滤器过滤路径
filterRegistrationBean.addUrlPatterns("/*");
// 忽略过滤的形式
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
}
4、实体类
@Entity
@Table(name = "city")
public class City {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
private String cityId;
private String cityName;
private String cityIntroduce;
public City(String cityId, String cityName, String cityIntroduce) {
this.cityId = cityId;
this.cityName = cityName;
this.cityIntroduce = cityIntroduce;
}
public City(String cityName, String cityIntroduce) {
this.cityName = cityName;
this.cityIntroduce = cityIntroduce;
}
public City() {
}
public String getCityId() {
return cityId;
}
public void setCityId(String cityId) {
this.cityId = cityId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getCityIntroduce() {
return cityIntroduce;
}
public void setCityIntroduce(String cityIntroduce) {
this.cityIntroduce = cityIntroduce;
}
}
5、Repository类
public interface CityRepository extends JpaRepository<City, String> {
void deleteByCityId(String id);
City findByCityId(String id);
}
6、controller类
@RestController
public class CityController {
@Autowired
private CityRepository cityRepository;
//http://localhost:8080/saveCity?cityName=北京&cityIntroduce=中国首都
@GetMapping(value = "saveCity")
public String saveCity(String cityName, String cityIntroduce) {
City city = new City(cityName, cityIntroduce);
cityRepository.save(city);
return "success";
}
//http://localhost:8080/deleteCity?cityId=2
@GetMapping(value = "deleteCity")
@Transactional
public String deleteCity(String cityId) {
cityRepository.deleteByCityId(cityId);
return "success";
}
//http://localhost:8080/updateCity?cityId=3&cityName=郑州&cityIntroduce=河南省省会
@GetMapping(value = "updateCity")
public String updateCity(String cityId, String cityName, String cityIntroduce) {
City city = new City(cityId, cityName, cityIntroduce);
cityRepository.save(city);
return "success";
}
//http://localhost:8080/getCityById?cityId=3
@GetMapping(value = "getCityById")
public City getCityById(String cityId) {
City city = cityRepository.findByCityId(cityId);
return city;
}
}
7、启动项目
- 访问http://localhost:8080/druid/login.html
image.png -
登录
image.png
网友评论