NutzCN Logo
精华 Springboot里使用Nutz.dao与Druid
发布于 2630天前 作者 Howe 5230 次浏览 复制 上一个帖子 下一个帖子
标签:

最近使用微服务(这年头啥东西都要微服务),作为Nutz组里唯一一个打酱油的,难道要跟一般人一样用Springboot+MyBatis?
这不是我风格呀,看了下Onekey的demo,发现居然要写application.yml,yml之类的东西最讨厌了。。
所以直接改写了下,基本上不需要啥配置的,springboot-nutz-starter是个好东西,直接Nutz.dao、Nutz.Json用起来,
废话少说下面贴代码。

pom.xml
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
4.0.0

<groupId>cn.nutz</groupId>
<artifactId>sb-nutz</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>cyxapiv2</name>
<url>http://maven.aliyun.com</url>
<description>project for Caiyouxi</description>

<repositories>
    <repository>
       <id>nutz</id>
       <url>https://jfrog.nutz.cn/artifactory/jcenter</url>
    </repository>
    <repository>
       <id>nutz-snapshots</id>
       <url>https://jfrog.nutz.cn/artifactory/snapshots</url>
       <snapshots>
         <enabled>true</enabled>
         <updatePolicy>always</updatePolicy>
       </snapshots>
       <releases>
         <enabled>false</enabled>
       </releases>
    </repository>
</repositories>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
       <groupId>org.nutz</groupId>
       <artifactId>nutz-plugins-spring-boot-starter</artifactId>
       <version>1.r.63-SNAPSHOT</version>
    </dependency>

    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-configuration-processor</artifactId>
       <optional>true</optional>
    </dependency>

    <dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>druid-spring-boot-starter</artifactId>
       <version>1.1.2</version>
    </dependency>

    <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>

</dependencies>

<build>
    <plugins>
       <plugin>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-maven-plugin</artifactId>
       </plugin>
    </plugins>
</build>


application.properties

server.port=80

数据源配置

https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter

spring.datasource.druid.url=jdbc:mysql://120.24.240.16:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false
spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.username=test
spring.datasource.druid.password=l6ZzXMs8PDVhexy4hSPBUMZ0rqGhxX5KJwOBptltZ5c5KlV6cgtUzAul0ERVjE2SnB7qUUq3g1+pa04MDlqJYQ==

配置 connection-properties,启用加密,配置公钥。

spring.datasource.druid.connection-properties=config.decrypt=true;config.decrypt.key=MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKjST2Dg5nbaoFaUOxjiCz2Qzu9tMkGMRg7e0g2cE0gbHJhnDJlinZX1CIqMSdw47VuqJaUxMECm9hephb9qee0CAwEAAQ==

启动ConfigFilter

spring.datasource.druid.filter.config.enabled=true

初始化大小,最小,最大

spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20

配置获取连接等待超时的时间

spring.datasource.druid.max-wait=60000

配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒

spring.datasource.druid.time-between-eviction-runs-millis=60000

配置一个连接在池中最小生存的时间,单位是毫秒

spring.datasource.druid.min-evictable-idle-time-millis=300000

检测连接是否有效的sql

spring.datasource.druid.validation-query=SELECT 'x'
spring.datasource.druid.validation-query-timeout=60000
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false

PSCache Mysql下建议关闭

spring.datasource.druid.pool-prepared-statements=false
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=-1

spring.datasource.druid.max-open-prepared-statements= #等价于上面的max-pool-prepared-statement-per-connection-size

配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙

spring.datasource.druid.filters=stat,wall,log4j

WebStatFilter配置,说明请参考Druid Wiki,配置_配置WebStatFilter

启动项目后访问 http://127.0.0.1:8080/druid

是否启用StatFilter默认值true

spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*

缺省sessionStatMaxCount是1000个

spring.datasource.druid.web-stat-filter.session-stat-max-count=1000

关闭session统计功能

spring.datasource.druid.web-stat-filter.session-stat-enable=false

配置principalSessionName,使得druid能够知道当前的session的用户是谁

如果你session中保存的是非string类型的对象,需要重载toString方法

spring.datasource.druid.web-stat-filter.principalSessionName=xxx.user

如果user信息保存在cookie中,你可以配置principalCookieName,使得druid知道当前的user是谁

spring.datasource.druid.web-stat-filter.principalCookieName=xxx.user

druid 0.2.7版本开始支持profile,配置profileEnable能够监控单个url调用的sql列表。

spring.datasource.druid.web-stat-filter.profile-enable=false

StatViewServlet配置,说明请参考Druid Wiki,配置_StatViewServlet配置

是否启用StatViewServlet默认值true

spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.urlPattern=/druid/*

禁用HTML页面上的“Reset All”功能

spring.datasource.druid.stat-view-servlet.resetEnable=false

用户名

spring.datasource.druid.stat-view-servlet.loginUsername=admin

密码

spring.datasource.druid.stat-view-servlet.loginPassword=admin

IP白名单(没有配置或者为空,则允许所有访问)

spring.datasource.druid.stat-view-servlet.allow=127.0.0.1,192.168.163.1

IP黑名单 (存在共同时,deny优先于allow)

spring.datasource.druid.stat-view-servlet.deny=192.168.1.73

日志配置

logging.level.com.caiyouxi=debug
logging.level.org.springframework.web=debug
logging.level.org.springframework.transaction=debug
logging.level.org.mybatis=debug

debug=false

```

工程结构
TIM截图20170909174213.jpg

项目代码
[https://gitee.com/howe/springboot-nutz-api-demo]

8 回复

又一个精华帖

来自美丽的 NutzCN

相信Nutz完全也可以打造一个微服务的!

@zozoh






+++++ +++++++++ ++++++++++++++++++++ +++++++++++++++++++ +++++++++++++++I7+++++ +++++++++++++++~ =++= ++++++++++++++ ~7=.==== ++++++++++++++I~~ ~====== +++++++++++++ ~~~:======== ++++++++++++ ~~~~~~~====== ++++++++++: ~~~~~~~~:~===== +++++++ == ~=++~~~=:~====== ++++ ======~~ ~~?:~======= + ==========7~~:~======== ========7~I:~========= ====== ~:~========== ======~~========== =============== =========== ' ███╗ ██╗██╗ ██╗████████╗███████╗ ███████╗████████╗ █████╗ ██████╗ ████████╗███████╗██████╗ ' ████╗ ██║██║ ██║╚══██╔══╝╚══███╔╝ ██╔════╝╚══██╔══╝██╔══██╗██╔══██╗╚══██╔══╝██╔════╝██╔══██╗ ' ██╔██╗ ██║██║ ██║ ██║ ███╔╝█████╗███████╗ ██║ ███████║██████╔╝ ██║ █████╗ ██████╔╝ ' ██║╚██╗██║██║ ██║ ██║ ███╔╝ ╚════╝╚════██║ ██║ ██╔══██║██╔══██╗ ██║ ██╔══╝ ██╔══██╗ ' ██║ ╚████║╚██████╔╝ ██║ ███████╗ ███████║ ██║ ██║ ██║██║ ██║ ██║ ███████╗██║ ██║ ' ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚══════╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ' powered by nutz.cn version 1.r.63 2017-11-14 14:17:11.348 INFO 6044 --- [ main] com.elvish.oda.OdaApplication : Starting OdaApplication on DESKTOP-ENB3GMH with PID 6044 (C:\Users\Elvish\git\oda\target\classes started by Elvish in C:\Users\Elvish\git\oda) 2017-11-14 14:17:11.355 INFO 6044 --- [ main] com.elvish.oda.OdaApplication : The following profiles are active: prod 2017-11-14 14:17:11.453 INFO 6044 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@12ed9db6: startup date [Tue Nov 14 14:17:11 CST 2017]; root of context hierarchy 2017-11-14 14:17:13.623 INFO 6044 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'com.elvish.oda.common.conf.shiro.ShiroManager' of type [com.elvish.oda.common.conf.shiro.ShiroManager] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2017-11-14 14:17:14.034 INFO 6044 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$8096de30] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2017-11-14 14:17:14.302 INFO 6044 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'shiroConfig' of type [com.elvish.oda.common.conf.ShiroConfig$$EnhancerBySpringCGLIB$$75e6b7ad] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2017-11-14 14:17:14.389 INFO 6044 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'shiroCacheManager' of type [org.apache.shiro.cache.MemoryConstrainedCacheManager] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2017-11-14 14:17:14.440 INFO 6044 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'securityManager' of type [org.apache.shiro.web.mgt.DefaultWebSecurityManager] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2017-11-14 14:17:14.585 INFO 6044 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'userService' of type [com.elvish.oda.busin.service.UserService] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2017-11-14 14:17:14.588 INFO 6044 --- [ main] org.apache.shiro.realm.AuthorizingRealm : No cache or cacheManager properties have been set. Authorization cache cannot be obtained. 2017-11-14 14:17:14.589 INFO 6044 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'myRealm' of type [com.elvish.oda.common.conf.shiro.MyRealm] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2017-11-14 14:17:14.643 INFO 6044 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'getAuthorizationAttributeSourceAdvisor' of type [org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2017-11-14 14:17:15.660 INFO 6044 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8085 (http) 2017-11-14 14:17:15.693 INFO 6044 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2017-11-14 14:17:15.702 INFO 6044 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.23 2017-11-14 14:17:16.158 INFO 6044 --- [ost-startStop-1] org.apache.jasper.servlet.TldScanner : At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. 2017-11-14 14:17:16.172 INFO 6044 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2017-11-14 14:17:16.173 INFO 6044 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4723 ms 2017-11-14 14:17:17.375 INFO 6044 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 2017-11-14 14:17:17.383 INFO 6044 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'statViewServlet' to [/druid/*] 2017-11-14 14:17:17.397 INFO 6044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2017-11-14 14:17:17.398 INFO 6044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2017-11-14 14:17:17.406 INFO 6044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2017-11-14 14:17:17.406 INFO 6044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2017-11-14 14:17:17.415 INFO 6044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'webStatFilter' to urls: [/*] 2017-11-14 14:17:17.415 INFO 6044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'shiroFilter' to: [/*] 2017-11-14 14:17:20.085 ERROR 6044 --- [ main] o.s.b.b.PropertiesConfigurationFactory : Properties configuration failed validation 2017-11-14 14:17:20.092 ERROR 6044 --- [ main] o.s.b.b.PropertiesConfigurationFactory : Field error in object 'spring.datasource.druid' on field 'driver': rejected value [com.mysql.jdbc.Driver]; codes [typeMismatch.spring.datasource.druid.driver,typeMismatch.driver,typeMismatch.java.sql.Driver,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [spring.datasource.druid.driver,driver]; arguments []; default message [driver]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Driver' for property 'driver'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.sql.Driver' for property 'driver': no matching editors or conversion strategy found] 2017-11-14 14:17:20.100 WARN 6044 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Could not bind properties to DruidDataSourceWrapper (prefix=spring.datasource.druid, ignoreInvalidFields=false, ignoreUnknownFields=true, ignoreNestedProperties=false); nested exception is org.springframework.validation.BindException: org.springframework.boot.bind.RelaxedDataBinder$RelaxedBeanPropertyBindingResult: 1 errors Field error in object 'spring.datasource.druid' on field 'driver': rejected value [com.mysql.jdbc.Driver]; codes [typeMismatch.spring.datasource.druid.driver,typeMismatch.driver,typeMismatch.java.sql.Driver,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [spring.datasource.druid.driver,driver]; arguments []; default message [driver]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Driver' for property 'driver'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.sql.Driver' for property 'driver': no matching editors or conversion strategy found] 2017-11-14 14:17:20.106 INFO 6044 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat] 2017-11-14 14:17:20.182 INFO 6044 --- [ main] utoConfigurationReportLoggingInitializer : Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled. 2017-11-14 14:17:20.192 ERROR 6044 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: Binding to target { CreateTime:"2017-11-14 14:17:17", ActiveCount:0, PoolingCount:0, CreateCount:0, DestroyCount:0, CloseCount:0, ConnectCount:0, Connections:[ ] } failed: Property: spring.datasource.druid.driver Value: com.mysql.jdbc.Driver Reason: Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Driver' for property 'driver'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.sql.Driver' for property 'driver': no matching editors or conversion strategy found Action: Update your application's configuration

我的yml配置是

spring:
  profiles:
    active: prod
    
  datasource:
    druid:
      driver: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/springboot
      username: root
      password: 123456
      # 启动ConfigFilter
      filter:
        config:
          enabled: true
      # 初始化大小,最小,最大
      initial-size: 5
      min-idle: 5
      max-active: 100
      # 配置获取连接等待超时的时间
      max-wait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      time-between-eviction-runs-millis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      min-evictable-idle-time-millis: 300000
      # 检测连接是否有效的sql
      validation-query: select 'x'
      validation-query-timeout: 60000
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      # PSCache Mysql下建议关闭
      pool-prepared-statements: false
      max-pool-prepared-statement-per-connection-size: -1
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filters: stat,wall,log4j
    
  mvc:
    view:
      prefix: /WEB-INF/jsp
      suffix: .jsp
    
logging:
  level: 
    root: info
  file: log/oda.log
  
server:
  jsp-servlet:
    init-parameters:
      development: true

driver配置错了吗?应如何解决问题

去掉driver: com.mysql.jdbc.Driver ,不需要配置的

一直用 nutz-plugins-spring-boot-starter coding起来带风啊

启动器内置了baseService 用起来更带风

添加回复
请先登陆
回到顶部