前置工作
- 瞭解Druid、瞭解Mybatis、瞭解SpringMVC集成mybatis、瞭解 dataSource
- 瞭解 @Configuration標籤
- 瞭解
dataSource、Mybatis配置
創建dbserver工程
- 引入druid、mysql、mybatis
- 因爲使用log4j2、thymeleaf引入了其他jar包
- 引入的包中需要排除相沖突的jar
build.gradle
apply plugin: 'org.springframework.boot'
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:" + springCloudVersion
mavenBom "org.springframework.boot:spring-boot-starter:"+ springBootVersion
}
}
repositories {
mavenCentral()
}
dependencies {
compile ('org.springframework.boot:spring-boot-starter-web:'+springBootVersion)
compile('org.springframework.cloud:spring-cloud-starter-eureka')
compile ('mysql:mysql-connector-java:'+mysqlVersion)
compile ('com.alibaba:druid:'+druidVersion)
compile ('org.mybatis:mybatis-spring:'+mybatisSpringBootVersion)
compile ('org.mybatis:mybatis:'+mybatisVersion)
compile('org.springframework.boot:spring-boot-starter-log4j2')
compile ('org.springframework.boot:spring-boot-starter-thymeleaf')
compile ('net.sourceforge.nekohtml:nekohtml:'+nekoHtmlVersion)
compile('org.apache.logging.log4j:log4j-1.2-api:'+ log4jAPIVersion)
compile('org.springframework.boot:spring-boot-starter-jdbc')
compile('org.springframework.boot:spring-boot-starter-aop')
compile ('com.alibaba:fastjson:'+fastjsonVersion)
testCompile ('org.springframework.boot:spring-boot-starter-test')
testCompile group: 'junit', name: 'junit', version: '4.11'
}
configurations {
all*.exclude module: 'spring-boot-starter-logging'
all*.exclude module: 'logback-classic'
all*.exclude module: 'log4j-over-slf4j'
all*.exclude module: 'snappy-java'
}
jar {
baseName = 'db-server-bootcwenao'
}
創建DataConfig,使用@Configuration進行註解
/**
* @author cwenao
* @version $Id DataConfig.java, v 0.1 2017-01-24 17:43 cwenao Exp $$
*/
@Configuration
@EnableTransactionManagement
public class DataConfig {
@Bean(name="dataSource")
@ConfigurationProperties(prefix = "druid.datasource")
public DataSource dataSource() {
return new DruidDataSource();
}
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("config.message");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
}
配置dataSource相關信息,這裏使用了druid
application.yml
druid:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/kakme?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: 111111
#初始化連接數量,最大最小連接數
initialSize: 5
maxActive: 10
minIdle: 3
#獲取連接等待超時的時間
maxWait: 600000
#超過時間限制是否回收
removeAbandoned: true
#超過時間限制多長
removeAbandonedTimeout: 180
#配置間隔多久才進行一次檢測,檢測需要關閉的空閒連接,單位是毫秒
timeBetweenEvictionRunsMillis: 600000
#配置一個連接在池中最小生存的時間,單位是毫秒
minEvictableIdleTimeMillis: 300000
#用來檢測連接是否有效的sql,要求是一個查詢語句
validationQuery: SELECT 1 FROM DUAL
#申請連接的時候檢測
testWhileIdle: true
#申請連接時執行validationQuery檢測連接是否有效,配置爲true會降低性能
testOnBorrow: false
#歸還連接時執行validationQuery檢測連接是否有效,配置爲true會降低性能
testOnReturn: false
#打開PSCache,並且指定每個連接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 50
#屬性類型是字符串,通過別名的方式配置擴展插件,常用的插件有:
#監控統計用的filter:stat 日誌用的filter:log4j 防禦SQL注入的filter:wall
filters: stat
創建MybatisConfig,使用註解@Configuration、@EnableTransactionManagement、@AutoConfigureAfter({DataConfig.class})、@MapperScan(basePackages = {“com.bootcwenao.dbserver.mapper”})
- @AutoConfigureAfter : 表示此項在某項配置完成後在進行configure
- @MapperScan : 掃描mapper文件
MybatisConfig
/**
* @author cwenao
* @version $Id MybatisConfig.java, v 0.1 2017-01-24 17:38 cwenao Exp $$
*/
@Configuration
@EnableTransactionManagement
@AutoConfigureAfter({DataConfig.class})
@MapperScan(basePackages = {"com.bootcwenao.dbserver.mapper"})
public class MybatisConfig implements EnvironmentAware {
@Autowired
DataSource dataSource;
private RelaxedPropertyResolver propertyResolver;
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() {
try {
ResourcePatternResolver resourcePatternResolver;
resourcePatternResolver = new PathMatchingResourcePatternResolver();
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setTypeAliasesPackage(propertyResolver.getProperty("typeAliasesPackage"));
bean.setMapperLocations(resourcePatternResolver.getResources(propertyResolver.getProperty("mapper-locations")));
bean.setConfigLocation(new DefaultResourceLoader().getResource(propertyResolver.getProperty("configLocation")));
return bean.getObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Bean
public PlatformTransactionManager platformTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
/**
* Set the {@code Environment} that this object runs in.
*
* @param environment
*/
@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment,"mybatis.");
}
}
配置mybatis相關注入信息
application.yml
mybatis:
typeAliasesPackage: com.bootcwenao.dbserver.pojo,com.bootcwenao.dbserver.vo
mapper-locations: classpath:/com/bootcwenao/dbserver/mapper/*Mapper.xml
configLocation: classpath:/config/mybatis-spring.xml
創建mybatis-spring.xml 用於額外mybatis的信息配置,比如分頁
mybatis-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties>
<property name="dialect" value="mysql" />
</properties>
<settings>
<!-- 這個配置使全局的映射器啓用或禁用緩存。系統默認值是true,設置只是爲了展示出來 -->
<setting name="cacheEnabled" value="true" />
<!-- 全局啓用或禁用延遲加載。當禁用時,所有關聯對象都會即時加載。 系統默認值是true,設置只是爲了展示出來 -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- 允許或不允許多種結果集從一個單獨的語句中返回(需要適合的驅動)。 系統默認值是true,設置只是爲了展示出來 -->
<setting name="multipleResultSetsEnabled" value="true" />
<!--使用列標籤代替列名。不同的驅動在這方便表現不同。參考驅動文檔或充分測試兩種方法來決定所使用的驅動。 系統默認值是true,設置只是爲了展示出來 -->
<setting name="useColumnLabel" value="true" />
<!--允許 JDBC 支持生成的鍵。需要適合的驅動。如果設置爲 true 則這個設置強制生成的鍵被使用,儘管一些驅動拒絕兼容但仍然有效(比如
Derby)。 系統默認值是false,設置只是爲了展示出來 -->
<setting name="useGeneratedKeys" value="false" />
<!--配置默認的執行器。SIMPLE 執行器沒有什麼特別之處。REUSE 執行器重用預處理語句。BATCH 執行器重用語句和批量更新 系統默認值是SIMPLE,設置只是爲了展示出來 -->
<setting name="defaultExecutorType" value="SIMPLE" />
<!--設置超時時間,它決定驅動等待一個數據庫響應的時間。 系統默認值是null,設置只是爲了展示出來 -->
<setting name="defaultStatementTimeout" value="25000" />
</settings>
<!--<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql" />
<property name="offsetAsPageNum" value="true" />
<property name="rowBoundsWithCount" value="true" />
<property name="pageSizeZero" value="true" />
<property name="reasonable" value="true" />
</plugin>
</plugins>-->
</configuration>
引入thymeleaf
spring:
thymeleaf:
cache: false
mode: LEGACYHTML5
prefix: classpath:/web/
suffix: .html
content-type: text/html
表以及實體類等
創建表 account_info
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for account_info
-- ----------------------------
DROP TABLE IF EXISTS `account_info`;
CREATE TABLE `account_info` (
`id` varchar(64) NOT NULL,
`account_name` varchar(64) DEFAULT NULL COMMENT '用戶名',
`nick_name` varchar(64) DEFAULT NULL COMMENT '暱稱',
`mail` varchar(64) DEFAULT NULL COMMENT '郵箱',
`m_tel` varchar(64) DEFAULT NULL COMMENT '移動電話',
`land_tel` varchar(64) DEFAULT NULL COMMENT '固定電話',
`is_vip` int(1) DEFAULT NULL,
`password` varchar(128) DEFAULT NULL COMMENT '密碼',
`salt` varchar(32) DEFAULT NULL COMMENT '鹽值',
`head_image` varchar(258) DEFAULT NULL COMMENT '頭像',
`back_image` varchar(258) DEFAULT NULL COMMENT '背景圖',
`account_type` int(1) DEFAULT NULL COMMENT '',
`source` int(1) DEFAULT NULL COMMENT ,
`audit_status` int(1) DEFAULT NULL,
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`update_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`status` int(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
根據account_info表創建生成 entity、mapper、*.Mapper.xml、server 此處略
- entity、mapper放置在java下的package
- *.Mapper.xml放置在resources下同mapper的目錄結構下
創建 Controller、html頁面
UserInfoController
/**
* @author cwenao
* @version $Id UserInfoController.java, v 0.1 2017-01-25 18:35 cwenao Exp $$
*/
@Controller
public class UserInfoController {
@Autowired
AccountInfoServer accountInfoServerImpl;
@RequestMapping("/accountInfo")
public String accountInfo(String name, ModelMap modelMap) {
List<AccountInfo> accountInfoList = accountInfoServerImpl.selectByName(name);
modelMap.addAttribute("accountList", accountInfoList);
return "userinfo/accountInfo";
}
}
創建 accountInfo.html,放置在userinfo文件夾下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body >
<table>
<tr th:each="accountInfo:${accountList}">
<td th:text="${accountInfo.accountName}">aabbcc</td>
<td th:text="${accountInfo.salt}">123dds</td>
</tr>
</table>
</body>
</html>
apigateway中加入dbserver訪問
bootstrap.yml
zuul:
routes:
dbserver:
path: /dbserver/**
serviceId: DBSERVER
測試訪問
- 在account_info中加入一條數據
- 啓動discovery、configserver、apigateway、dbserver
訪問地址:http://localhost:10002/dbserver/accountInfo?name=cwenao
- http://localhost:10002 爲網關地址
- dbserver爲網關zuul 配置path
- accountInfo?name=cwenao 爲controller訪問地址
代碼
代碼請移步 Github參考地址
如有疑問請加公衆號(K171),如果覺得對您有幫助請 github start