springboot之druid连接postgersql11代码实践

x33g5p2x  于2021-12-24 转载在 其他  
字(6.3k)|赞(0)|评价(0)|浏览(443)

1.pom文件依赖

<!--数据库连接jdbc依赖-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>4.1.0.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--mysql链接依赖-->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
</dependency>
<!--阿里druid数据库链接依赖-->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid-spring-boot-starter</artifactId>
  <version>1.1.9</version>
</dependency>

<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-dbcp2</artifactId>
  <version>2.0.1</version>
</dependency>

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.1.15</version>
</dependency>

<dependency>
  <groupId>commons-codec</groupId>
  <artifactId>commons-codec</artifactId>
  <version>1.10</version>
</dependency>

2.application.yml文件配置

# postgresql 环境配置
server:
  port: 18005
  max-http-header-size: 8192
logging:
  level:
    root: info
spring:
  datasource:
#    url: jdbc:postgresql://10.101.15.59:5432/postgres?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false&useSSL=false
    url: jdbc:postgresql://10.101.15.59:5432/postgres
    username: root
    password: 123abc
#   driver-class-name: com.mysql.jdbc.Driver
#    driver-class-name: org.postgresql.Driver
    driverClassName: org.postgresql.Driver
#    driverClass: org.postgresql.Driver
    platform: postgres
    type: com.alibaba.druid.pool.DruidDataSource
#   type: org.apache.commons.dbcp2.BasicDataSource
    initialization-mode: always

    # ============================== druid ============================== #
    druid:
      #最大活跃数
      maxActive: 20
      #初始化数量
      initialSize: 1
      #最大连接等待超时时间
      maxWait: 60000
      #打开PSCache,并且指定每个连接PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      #通过connectionProperties属性来打开mergeSql功能;慢SQL记录
      #connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      minIdle: 1
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: select 1 from dual
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      #配置监控统计拦截的filters,去掉后监控界面sql将无法统计,'wall'用于防火墙
      filters: stat, wall, log4j
  jpa:
    show_sql: true
    database-platform: org.hibernate.dialect.PostgreSQL9Dialect
    # database-platform: cn.luutqf.springboot.dialect.JsonbPostgresDialect
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect
        hbm2ddl.auto: update
        jdbc.lob.non_contextual_creation: true
        format_sql: true
        temp:
          # 兼容SpringBoot2.X, 关闭 Hibernate尝试验证PostgreSQL的CLOB特性
          use_jdbc_metadata_defaults: false

3.Config代码配置

package org.fiend.config;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.fiend.common.jdbc.JdbcDao;
import org.fiend.common.jdbc.impl.JdbcDaoImpl;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * postgresql data source config
 * @author fiend 2018/12/5
 */
@Configuration
public class PgsDataSourceConfig {
    @Bean(name = "jdbcDao")
    @Qualifier("jdbcDao")
    public JdbcDao jdbcDao(@Qualifier("jdbcTemplate") JdbcTemplate jdbcTemplate) {
        return new JdbcDaoImpl(jdbcTemplate);
    }

    @Bean(name = "jdbcTemplate")
    @Qualifier("jdbcTemplate")
    public JdbcTemplate jdbcTemplate(@Qualifier("dataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean(name = "dataSource")
    @Qualifier("dataSource")
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource DataSource() {
        return DataSourceBuilder.create().type(dataSourceType).build();
    }

    @Value("${spring.datasource.type}")
    private Class<? extends DataSource> dataSourceType;

    /**
     * 配置监控服务器
     * @return 返回监控注册的servlet对象
     */
    @Bean
    @SuppressWarnings("unchecked")
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean servletRegistrationBean =
                new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // 添加IP白名单
        servletRegistrationBean.addInitParameter("allow", "192.168.25.125,127.0.0.1");
        // 添加IP黑名单,当白名单和黑名单重复时,黑名单优先级更高
        servletRegistrationBean.addInitParameter("deny", "192.168.25.123");
        // 添加控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", "druid");
        servletRegistrationBean.addInitParameter("loginPassword", "123456");
        // 是否能够重置数据
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    /**
     * 配置服务过滤器
     * @return 返回过滤器配置对象
     */
    @Bean
    @SuppressWarnings("unchecked")
    public FilterRegistrationBean statFilter() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        // 添加过滤规则
        filterRegistrationBean.addUrlPatterns("/*");
        // 忽略过滤格式
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*,");
        return filterRegistrationBean;
    }
}

4.读取数据库代码

/**
 * @author fiend
 */
@Service
public class HomeService extends AbstractService {
	Logger log = LoggerFactory.getLogger(getClass());

	public JSONObject getUserInfo() {
        String sql = "select * from public.user";
	    JSONObject json = new JSONObject();
        List<User> userList = jdbcDao.queryForList(sql, new Object[]{}, User.class);
        json.put("userInfoList", userList);

        return json;
    }
}

相关文章