王八跪求绿主开发老婆!Srping3.X整合Mybati...

mybatis-spring-boot-autoconfigure – MyBatis Sring-BootStarter | Reference Documentation
mybatis-spring-boot-autoconfigure
Version: 2.0.0-SNAPSHOT
Introduction
What is MyBatis-Spring-Boot-Starter?
The MyBatis-Spring-Boot-Starter help you build quickly MyBatis applications on top of the
By using this module you will achieve:
Build standalone applications.
Reduce the boilerplate to almost zero.
Less XML configuration.
Requirements
The MyBatis-Spring-Boot-Starter requires Java 6 or higher and the following MyBatis-Spring and Spring Boot versions:
MyBatis-Spring-Boot-Starter
Spring Boot
1.3.x (1.3.1)
1.3 or higher
1.5 or higher
1.2.x (1.2.1)
1.3 or higher
1.4 or higher
1.1.x (1.1.1)
1.3 or higher
1.3 or higher
1.0.x (1.0.2)
1.2 or higher
1.3 or higher
Installation
To use the MyBatis-Spring-Boot-Starter module, you just need to include the
mybatis-spring-boot-autoconfigure.jar file and its dependencies(mybatis.jar, mybatis-spring.jar and etc ...) in the classpath.
If you are using Maven just add the following dependency to your pom.xml:
&dependency&
&groupId&org.mybatis.spring.boot&/groupId&
&artifactId&mybatis-spring-boot-starter&/artifactId&
&version&2.0.0-SNAPSHOT&/version&
&/dependency&
If using gradle add this to your build.gradle:
dependencies {
compile(&org.mybatis.spring.boot:mybatis-spring-boot-starter:2.0.0-SNAPSHOT&)
Quick Setup
As you may already know, to use MyBatis with Spring you need at least an SqlSessionFactory
and at least one mapper interface.
MyBatis-Spring-Boot-Starter will:
Autodetect an existing DataSource.
Will create and register an instance of a SqlSessionFactory passing that DataSource as an input using the SqlSessionFactoryBean.
Will create and register an instance of a SqlSessionTemplate got out of the SqlSessionFactory.
Autoscan your mappers, link them to the SqlSessionTemplate and register them to Spring context so they can be injected into your beans.
Suppose we have the following mapper:
public interface CityMapper {
@Select(&SELECT * FROM CITY WHERE state = #{state}&)
City findByState(@Param(&state&) String state);
You just need to create a normal Spring boot application and let the mapper be injected like follows(available on Spring 4.3+):
@SpringBootApplication
public class SampleMybatisApplication implements CommandLineRunner {
private final CityMapper cityM
public SampleMybatisApplication(CityMapper cityMapper) {
this.cityMapper = cityM
public static void main(String[] args) {
SpringApplication.run(SampleMybatisApplication.class, args);
public void run(String... args) throws Exception {
System.out.println(this.cityMapper.findByState(&CA&));
This is all you have to do. You application can now be run as a normal Spring Boot application.
Advanced scanning
The MyBatis-Spring-Boot-Starter will search, by default, for mappers marked with the @Mapper annotation.
You may want to specify a custom annotation or a marker interface for scanning. If so, you must use the @MapperScan annotation.
See more about it in the
The MyBatis-Spring-Boot-Starter will not start the scanning process if it finds at least one MapperFactoryBean in the
Spring's context so if you want to stop the scanning at all you should register your mappers explicitly with @Bean methods.
Using an SqlSession
An instance of a SqlSessionTemplate is created and added to the Spring context, so you can use the MyBatis API
letting it be injected into your beans like follows(available on Spring 4.3+):
@Component
public class CityDao {
private final SqlSession sqlS
public CityDao(SqlSession sqlSession) {
this.sqlSession = sqlS
public City selectCityById(long id) {
return this.sqlSession.selectOne(&selectCityById&, id);
Configuration
As any other Spring Boot application a MyBatis-Spring-Boot-Application configuration parameters are stored inside the
application.properties(or application.yml).
MyBatis uses the prefix mybatis for its properties
Available properties are:
Description
config-location
Location of MyBatis xml config file.
check-config-location
Indicates whether perform presence check of the MyBatis xml config file.
mapper-locations
Locations of Mapper xml config file.
type-aliases-package
Packages to search for type aliases. (Package delimiters are &,; \t\n&)
type-handlers-package
Packages to search for type handlers. (Package delimiters are &,; \t\n&)
executor-type
Executor type: SIMPLE, REUSE, BATCH.
configuration-properties
Externalized properties for MyBatis configuration. Specified properties can be used as placeholder on MyBatis config file and Mapper file.
For detail see the
configuration
A MyBatis Configuration bean. About available properties see the .
NOTE This property cannot be used at the same time with the config-location.
For example:
# application.properties
mybatis.type-aliases-package=com.example.domain.model
mybatis.type-handlers-package=com.example.typehandler
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.configuration.default-fetch-size=100
mybatis.configuration.default-statement-timeout=30
# application.yml
type-aliases-package: com.example.domain.model
type-handlers-package: com.example.typehandler
configuration:
map-underscore-to-camel-case: true
default-fetch-size: 100
default-statement-timeout: 30
Using a ConfigurationCustomizer
The MyBatis-Spring-Boot-Starter provide opportunity to customize a MyBatis configuration generated by auto-configuration using Java Config.
The MyBatis-Spring-Boot-Starter will search beans that implements the ConfigurationCustomizer interface by automatically,
and call a method that customize a MyBatis configuration. (Available since 1.2.1 or above)
For example:
// @Configuration class
ConfigurationCustomizer mybatisConfigurationCustomizer() {
return new ConfigurationCustomizer() {
public void customize(Configuration configuration) {
// customize ...
Detecting MyBatis components
The MyBatis-Spring-Boot-Starter will detects beans that implements following interface provided by MyBatis.
Running Samples
The project provides two samples so you play and experiment with them:
Description
Show the simplest scenario with just a mapper and a bean where the mapper is injected into. This is the sample we saw in the Quick Setup section.
Shows how to use a Mapper that has its statements in an xml file and Dao that uses an SqlSesionTemplate.
Copyright &2015&#x
All rights reserved.1,002 views
基于spring boot开发的微服务应用,与MyBatis如何集成?
可行的方法有:
基于XML或者Java Config,构建必需的对象,配置MyBatis。
使用MyBatis官方提供的组件,实现MyBatis的集成。
建议参考如下文章,完成集成的验证。
由于不是本文的重点,因此不附上样例。
有如下步骤:
修改pom.xml,增加软件依赖
&org.mybatis.spring.boot&
&mybatis-spring-boot-starter&
&mysql-connector-java&
修改application.yml,增加数据源的定义
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
修改application.yml,增加MyBatis的配置
type-aliases-package: com.example.domain.model
type-handlers-package: com.example.typehandler
configuration:
map-underscore-to-camel-case: true
default-fetch-size: 100
default-statement-timeout: 30
日志的配置
通过观察日志,可有效的分析MyBatis生成的SQL,检查SQL配置的正确性。
修改application.yml,增加如下配置
jackieathome:
mapper: DEBUG
其中net.jackieathome.db.mapper下定义了访问数据库的mapper接口。
输出的日志样例如下
11:32:23.266 DEBUG 27801 --- [io-11002-exec-1] n.j.db.mapper.UserMapper.createUser
Preparing: insert into `user`(id, name, password) values(?, ?, ?)
11:32:23.293 DEBUG 27801 --- [io-11002-exec-1] n.j.db.mapper.UserMapper.createUser
: ==& Parameters: id(String), null, null
11:32:23.366 DEBUG 27801 --- [io-11002-exec-1] n.j.db.mapper.UserMapper.createUser
Updates: 1
11:32:23.372 DEBUG 27801 --- [io-11002-exec-1] n.j.db.mapper.UserMapper.findUserById
Preparing: select * from `user` where id = ?
11:32:23.373 DEBUG 27801 --- [io-11002-exec-1] n.j.db.mapper.UserMapper.findUserById
: ==& Parameters: id(String)
11:32:23.417 DEBUG 27801 --- [io-11002-exec-1] n.j.db.mapper.UserMapper.findUserById
事务的使用
依据MyBatis的官方文档,允许用户将事务交给Spring来管理,使用编程和注解来控制事务。这里以注解方式来举例说明使用方法,样例代码如下:
mapper的定义,如下
package net.jackieathome.db.
import java.util.L
import org.apache.ibatis.annotations.M
import org.apache.ibatis.annotations.P
import net.jackieathome.bean.U
public interface UserMapper {
void createUser(User user);
User findUserById(@Param("id") String id);
数据库访问的中间层代码,对上述mapper进行了封装。
使用@Transactional标记该类,表明该类的公有方法全部都启用了事务的支持。关于@Transactional的使用,可以参考相关的官方文档。
package net.jackieathome.
import java.util.ArrayL
import java.util.L
import org.springframework.beans.factory.annotation.A
import org.
import org.springframework.transaction.annotation.T
import net.jackieathome.bean.U
import net.jackieathome.db.mapper.UserM
@Component
@Transactional
public class UserDao {
@Autowired
private UserMapper userM
public List&String& createBatch() {
long time = System.currentTimeMillis() / 1000;
User user = null;
List&String& ids = new ArrayList&&();
String id = "id" +
String name = "name" +
String password = "password" +
user = new User();
user.setId(id);
user.setName(name);
user.setPassword(password);
userMapper.createUser(user);
ids.add(id);
user = new User();
user.setId(id);
user.setName(name);
user.setPassword(password);
userMapper.createUser(user);
ids.add(id);
业务层实现
package net.jackieathome.
import java.util.L
import org.springframework.beans.factory.annotation.A
import org.springframework.web.bind.annotation.PathV
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RestC
import net.jackieathome.bean.U
import net.jackieathome.dao.UserD
import net.jackieathome.db.mapper.UserM
@RestController
public class UserController {
@Autowired
private UserMapper userM
@Autowired
private UserDao userD
@RequestMapping(method = RequestMethod.GET, value = "/user/create/batch")
public List&User& createBatch() {
userDao.createBatch();
catch (Exception e)
return userMapper.loadAllUsers();
从实际测试看,上述事务的实现有效,可保证当数据出现主键冲突时,事务中的插入操作可全部撤销,不会出现部分数据插入成功、部分失败的现象。
注意事项:
由于注解事务的实现依赖Spring AOP,因此只有当注入行为存在时,注解事务的控制才会生效。
假如在上述UserController类中定义createBatch方法,并且使用注解@Transactional标记,经验证可确认此时注解事务是无效的。
假如在上述UserDao中定义了多个公有方法,存在相互调用的行为,基于相同的原因,这些方法相互调用时注解事务并不会生效。如果确实需要保证事务可用,可以考虑调整类的设计或者使用编程的方式来控制事务。
Spring Boot与MyBatis
Spring与MyBatis
1,271 views
基于当前的1.5.2.RELEASE的Spring Boot。
依照官方文档,如果增加了如下依赖的配置,或者类路径中存在spring-boot-starter-jdbc的jar,那么已默认启用了数据库链接池。
&org.springframework.boot&
&spring-boot-starter-jdbc&
Spring Boot选择数据库链接池实现的判断逻辑:
检查Tomcat的数据库链接池实现是否可用,如可用,则启用。使用spring.datasource.tomcat.*可以控制链接池的行为。
检查HikariCP是否可用,如可用,则启用。使用spring.datasource.hikari.*可以控制链接池的行为。
检查Commons DBCP是否可用,如可用,则启用;但Spring Boot不建议在生产环境使用该链接池的实现。
检查Commons DBCP2是否可用,如可用,则启用。使用spring.datasource.dbcp2.*可以控制链接池的行为。
使用tomcat-jdbc时,可在application.yml增加配置项spring.datasource.tomcat.*来控制链接池的行为。比如如下配置。
datasource:
url: jdbc:mysql://localhost:3306/jackieathome?useSSL=false
username: root
password: mypassword
# 6.x版本的MySQL JDBC驱动类为com.mysql.cj.jdbc.Driver
# 5.X版本的MySQL JDBC驱动类为com.mysql.jdbc.Driver
driver-class-name: com.mysql.cj.jdbc.Driver
max-wait: 10000
max-active: 30
test-on-borrow: true
# 传递MySQL JDBC特有的参数
db-properties:
logger: net.jackieathome.db.customized.MySQLLogger
gatherPerfMetrics: 'true'
profileSQL: 'true'
reportMetricsIntervalMillis: '60000'
logSlowQueries: 'true'
explainSlowQueries: 'true'
# 关闭其它软件的日志,减少干扰
org: ERROR
net: ERROR
com: ERROR
# 开启MySQL JDBC驱动的日志
MySQL: DEBUG
上述spring.datasource.tomcat.*代表的配置项,可参考tomcat-jdbc的官方文档或者。
依据tomcat-jdbc的文档,如需要向数据库的JDBC驱动传入控制参数,可以使用db-properties字段。需要注意的是,当使用MySQL驱动时,控制参数的值需要强制转换为字符串,否则创建数据库链接时会报错。配置方法如上述样例中的 reportMetricsIntervalMillis: '60000'和logSlowQueries: 'true'。
依照MySQL JDBC驱动文档,可以配置一个日志记录器,用于记录其工作时的输出,如下是实现样例。
package net.jackieathome.db.
import org.slf4j.L
import org.slf4j.LoggerF
public class MySQLLogger implements com.mysql.cj.api.log.Log {
private static Logger LOG;
public MySQLLogger(String name) {
LOG = LoggerFactory.getLogger(name);
public boolean isDebugEnabled() {
return LOG.isDebugEnabled();
public boolean isErrorEnabled() {
return LOG.isErrorEnabled();
public boolean isFatalEnabled() {
return LOG.isErrorEnabled();
public boolean isInfoEnabled() {
return LOG.isInfoEnabled();
public boolean isTraceEnabled() {
return LOG.isTraceEnabled();
public boolean isWarnEnabled() {
return LOG.isWarnEnabled();
public void logDebug(Object msg) {
LOG.debug("{}", msg);
public void logDebug(Object msg, Throwable thrown) {
LOG.debug("{}", msg, thrown);
public void logError(Object msg) {
LOG.error("{}", msg);
public void logError(Object msg, Throwable thrown) {
LOG.error("{}", msg, thrown);
public void logFatal(Object msg) {
LOG.error("{}", msg);
public void logFatal(Object msg, Throwable thrown) {
LOG.error("{}", msg, thrown);
public void logInfo(Object msg) {
("{}", msg);
public void logInfo(Object msg, Throwable thrown) {
("{}", msg, thrown);
public void logTrace(Object msg) {
LOG.trace("{}", msg);
public void logTrace(Object msg, Throwable thrown) {
LOG.trace("{}", msg, thrown);
public void logWarn(Object msg) {
LOG.warn("{}", msg);
public void logWarn(Object msg, Throwable thrown) {
LOG.warn("{}", msg, thrown);
同时修改application.yml,增加相应的日志配置,如下。
# 开启MySQL JDBC驱动的日志
MySQL: DEBUG
如下是MySQL JDBC驱动输出的样例日志。
00:51:32.626 QUERY created: Sun Apr 16 00:51:32 CST 2017 duration: 0 connection: 93 statement: 1 resultset: 1 message: /* mysql-connector-java-6.0.6 ( Revision: 3dab84f4d9bede3cdd14d57b99e9e98a02a5b97d ) */SELECT
@@session.auto_increment_increment AS auto_increment_increment, @@character_set_client AS character_set_client, @@character_set_connection AS character_set_connection, @@character_set_results AS character_set_results, @@character_set_server AS character_set_server, @@init_connect AS init_connect, @@interactive_timeout AS interactive_timeout, @@license AS license, @@lower_case_table_names AS lower_case_table_names, @@max_allowed_packet AS max_allowed_packet, @@net_buffer_length AS net_buffer_length, @@net_write_timeout AS net_write_timeout, @@query_cache_size AS query_cache_size, @@query_cache_type AS query_cache_type, @@sql_mode AS sql_mode, @@system_time_zone AS system_time_zone, @@time_zone AS time_zone, @@tx_isolation AS tx_isolation, @@wait_timeout AS wait_timeout
00:51:32.629 FETCH created: Sun Apr 16 00:51:32 CST 2017 duration: 36 connection: 93 statement: 1 resultset: 1
00:51:32.639 QUERY created: Sun Apr 16 00:51:32 CST 2017 duration: 1 connection: 93 statement: 999 resultset: 0 message: SET NAMES latin1
00:51:32.640 FETCH created: Sun Apr 16 00:51:32 CST 2017 duration: 0 connection: 93 statement: 999 resultset: 0
00:51:32.642 QUERY created: Sun Apr 16 00:51:32 CST 2017 duration: 2 connection: 93 statement: 999 resultset: 0 message: SET character_set_results = NULL
00:51:32.643 FETCH created: Sun Apr 16 00:51:32 CST 2017 duration: 0 connection: 93 statement: 999 resultset: 0
00:51:32.645 QUERY created: Sun Apr 16 00:51:32 CST 2017 duration: 0 connection: 93 statement: 999 resultset: 0 message: SET autocommit=1
00:51:32.646 FETCH created: Sun Apr 16 00:51:32 CST 2017 duration: 0 connection: 93 statement: 999 resultset: 0
00:51:32.667 QUERY created: Sun Apr 16 00:51:32 CST 2017 duration: 1 connection: 94 statement: 2 resultset: 2 message: /* mysql-connector-java-6.0.6 ( Revision: 3dab84f4d9bede3cdd14d57b99e9e98a02a5b97d ) */SELECT
@@session.auto_increment_increment AS auto_increment_increment, @@character_set_client AS character_set_client, @@character_set_connection AS character_set_connection, @@character_set_results AS character_set_results, @@character_set_server AS character_set_server, @@init_connect AS init_connect, @@interactive_timeout AS interactive_timeout, @@license AS license, @@lower_case_table_names AS lower_case_table_names, @@max_allowed_packet AS max_allowed_packet, @@net_buffer_length AS net_buffer_length, @@net_write_timeout AS net_write_timeout, @@query_cache_size AS query_cache_size, @@query_cache_type AS query_cache_type, @@sql_mode AS sql_mode, @@system_time_zone AS system_time_zone, @@time_zone AS time_zone, @@tx_isolation AS tx_isolation, @@wait_timeout AS wait_timeout
Spring的链接池配置
Spring Boot的链接池的配置
Tomcat的链接池的配置
MySQL JDBC
1,403 views
基于Spring Boot 1.5.2.RELEASE版本,一方面验证与Redis的集成方法,另外了解使用方法。
修改pom.xml,增加如下内容。
&org.springframework.boot&
&spring-boot-starter-data-redis&
修改application.yml,增加如下内容。
host: localhost
port: 6379
max-idle: 8
min-idle: 0
max-active: 8
max-wait: -1
配置Redis缓存
package net.jackieathome.
import java.lang.reflect.M
import org.springframework.cache.CacheM
import org.springframework.cache.annotation.CachingConfigurerS
import org.springframework.cache.annotation.EnableC
import org.springframework.cache.interceptor.KeyG
import org.springframework.context.annotation.B
import org.springframework.context.annotation.C
import org.springframework.data.redis.cache.RedisCacheM
import org.springframework.data.redis.connection.RedisConnectionF
import org.springframework.data.redis.core.RedisT
import org.springframework.data.redis.core.StringRedisT
import org.springframework.data.redis.serializer.Jackson2JsonRedisS
import com.fasterxml.jackson.annotation.JsonAutoD
import com.fasterxml.jackson.annotation.PropertyA
import com.fasterxml.jackson.databind.ObjectM
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
redisCacheManager.setDefaultExpiration(300);
return redisCacheM
public RedisTemplate&String, String& redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
验证集成后的效果
考虑到未来参与的项目基于MyBatis实现数据库访问,而利用缓存,可有效改善Web页面的交互体验,因此设计了如下两个验证方案。
在访问数据库的数据对象上增加缓存注解,定义缓存策略。从测试效果看,缓存有效。
页面控制器
package net.jackieathome.
import java.util.L
import org.springframework.beans.factory.annotation.A
import org.springframework.web.bind.annotation.PathV
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RestC
import net.jackieathome.bean.U
import net.jackieathome.dao.UserD
import net.jackieathome.db.mapper.UserM
@RestController
public class UserController {
@Autowired
private UserDao userD
@RequestMapping(method = RequestMethod.GET, value = "/user/id/{id}")
public User findUserById(@PathVariable("id") String id) {
return userDao.findUserById(id);
@RequestMapping(method = RequestMethod.GET, value = "/user/create")
public User createUser() {
long time = System.currentTimeMillis() / 1000;
String id = "id" +
User user = new User();
user.setId(id);
userDao.createUser(user);
return userDao.findUserById(id);
Mapper定义
package net.jackieathome.db.
import java.util.L
import org.apache.ibatis.annotations.M
import org.apache.ibatis.annotations.P
import org.springframework.cache.annotation.CacheC
import org.springframework.cache.annotation.CacheP
import org.springframework.cache.annotation.C
import net.jackieathome.bean.U
public interface UserMapper {
void createUser(User user);
User findUserById(@Param("id") String id);
数据访问对象
package net.jackieathome.
import java.util.ArrayL
import java.util.L
import org.apache.ibatis.annotations.P
import org.slf4j.L
import org.slf4j.LoggerF
import org.springframework.beans.factory.annotation.A
import org.springframework.cache.annotation.CacheC
import org.springframework.cache.annotation.CacheP
import org.springframework.cache.annotation.C
import org.
import org.springframework.transaction.annotation.T
import net.jackieathome.bean.U
import net.jackieathome.db.mapper.UserM
@Component
@CacheConfig(cacheNames = "users")
@Transactional
public class UserDao {
private static final Logger LOG = LoggerFactory.getLogger(UserDao.class);
@Autowired
private UserMapper userM
@CachePut(key = "#p0.id")
public void createUser(User user) {
userMapper.createUser(user);
LOG.debug("create user=" + user);
@Cacheable(key = "#p0")
public User findUserById(@Param("id") String id) {
LOG.debug("find user=" + id);
return userMapper.findUserById(id);
直接在Mapper定义上增加缓存注解,控制缓存策略。从测试效果看,缓存有效,相比于方案一,测试代码更加简洁一些。
页面控制器
package net.jackieathome.
import java.util.L
import org.springframework.beans.factory.annotation.A
import org.springframework.web.bind.annotation.PathV
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RestC
import net.jackieathome.bean.U
import net.jackieathome.dao.UserD
import net.jackieathome.db.mapper.UserM
@RestController
public class UserController {
@Autowired
private UserMapper userM
@RequestMapping(method = RequestMethod.GET, value = "/user/id/{id}")
public User findUserById(@PathVariable("id") String id) {
return userMapper.findUserById(id);
@RequestMapping(method = RequestMethod.GET, value = "/user/create")
public User createUser() {
long time = System.currentTimeMillis() / 1000;
String id = "id" +
User user = new User();
user.setId(id);
userMapper.createUser(user);
return userMapper.findUserById(id);
Mapper定义
package net.jackieathome.db.
import java.util.L
import org.apache.ibatis.annotations.M
import org.apache.ibatis.annotations.P
import org.springframework.cache.annotation.CacheC
import org.springframework.cache.annotation.CacheP
import org.springframework.cache.annotation.C
import net.jackieathome.bean.U
@CacheConfig(cacheNames = "users")
public interface UserMapper {
@CachePut(key = "#p0.id")
void createUser(User user);
@Cacheable(key = "#p0")
User findUserById(@Param("id") String id);
上述两个测试方案并没有优劣之分,仅是为了验证缓存的使用方法,体现了不同的控制粒度,在实际的项目开发过程中,需要依据实际情况做不同的决断。
缓存相关的注解:
CacheConfig
CacheEvict
使用redis缓存
MyBatis的缓存特性
运行redis docker镜像的命令
sudo docker run --rm -d -p
1,232 views
docker笔记之构建nginx的Dockerfile
从源码构建nginx应用,可以参考。
PS:这份Dockerfile使用了alpine作为基础镜像,非常有特点,但对于Jackie这样的小白来说区别不大。
基于ubuntu的Dockerfile
FROM ubuntu:14.04
MAINTAINER Jackie "www.jackieathome.net"
ENV NGINX_VERSION 1.10.3
ENV OPENSSL_VERSION 1.0.2k
ENV PCRE_VERSION 8.40
ENV ZLIB_VERSION 1.2.11
ENV BUILD_ROOT /usr/local/src/nginx
RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak \
&& sed -i "s/archive\.ubuntu\.com/mirrors\.163\.com/g" /etc/apt/sources.list \
&& apt-get update \
&& apt-get -y install zip unzip curl make gcc g++ \
&& mkdir -p $BUILD_ROOT \
&& cd $BUILD_ROOT \
&& curl https://ftp.pcre.org/pub/pcre/pcre-$PCRE_VERSION.zip -o $BUILD_ROOT/pcre-$PCRE_VERSION.zip \
&& curl https://www.openssl.org/source/openssl-$OPENSSL_VERSION.tar.gz -o $BUILD_ROOT/openssl-$OPENSSL_VERSION.tar.gz \
&& curl http://www.zlib.net/zlib-$ZLIB_VERSION.tar.gz -o $BUILD_ROOT/zlib-$ZLIB_VERSION.tar.gz \
&& curl https://nginx.org/download/nginx-$NGINX_VERSION.tar.gz -o $BUILD_ROOT/nginx-$NGINX_VERSION.tar.gz \
&& tar vxzf nginx-$NGINX_VERSION.tar.gz \
&& unzip pcre-$PCRE_VERSION.zip \
&& tar vxfz zlib-$ZLIB_VERSION.tar.gz \
&& tar vxfz openssl-$OPENSSL_VERSION.tar.gz \
&& cd nginx-$NGINX_VERSION \
&& BUILD_CONFIG="\
--prefix=/etc/nginx \
--sbin-path=/usr/sbin/nginx \
--conf-path=/etc/nginx/nginx.conf \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--pid-path=/var/run/nginx.pid \
--lock-path=/var/run/nginx.lock \
--http-client-body-temp-path=/var/cache/nginx/client_temp \
--http-proxy-temp-path=/var/cache/nginx/proxy_temp \
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp \
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp \
--http-scgi-temp-path=/var/cache/nginx/scgi_temp \
--with-openssl=$BUILD_ROOT/openssl-$OPENSSL_VERSION \
--with-pcre=$BUILD_ROOT/pcre-$PCRE_VERSION \
--with-zlib=$BUILD_ROOT/zlib-$ZLIB_VERSION \
--with-http_ssl_module \
--with-http_v2_module \
--with-threads \
&& mkdir -p /var/cache/nginx \
&& ./configure $BUILD_CONFIG \
&& make && make install \
&& rm -rf $BUILD_ROOT \
&& apt-get -y remove zip unzip curl make gcc g++ \
&& apt-get -y autoremove \
&& rm -rf /var/lib/apt/lists/* \
&& cp /etc/apt/sources.list.bak /etc/apt/sources.list \
&& ln -sf /dev/stdout /var/log/nginx/access.log \
&& ln -sf /dev/stderr /var/log/nginx/error.log
EXPOSE 80 443
CMD ["nginx", "-g", ""]
基于centos的Dockerfile
FROM centos
MAINTAINER Jackie "www.jackieathome.net"
ENV NGINX_VERSION 1.10.3
ENV OPENSSL_VERSION 1.0.2k
ENV PCRE_VERSION 8.40
ENV ZLIB_VERSION 1.2.11
ENV BUILD_ROOT /usr/local/src/nginx
yum -y install curl \
&& mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup \
&& curl http://mirrors.163.com/.help/CentOS7-Base-163.repo -o /etc/yum.repos.d/CentOS7-Base-163.repo \
&& yum clean all \
&& yum makecache \
&& yum -y install gcc gcc-c++ make perl zip unzip \
&& mkdir -p $BUILD_ROOT \
&& cd $BUILD_ROOT \
&& curl https://ftp.pcre.org/pub/pcre/pcre-$PCRE_VERSION.zip -o $BUILD_ROOT/pcre-$PCRE_VERSION.zip \
&& curl https://www.openssl.org/source/openssl-$OPENSSL_VERSION.tar.gz -o $BUILD_ROOT/openssl-$OPENSSL_VERSION.tar.gz \
&& curl http://www.zlib.net/zlib-$ZLIB_VERSION.tar.gz -o $BUILD_ROOT/zlib-$ZLIB_VERSION.tar.gz \
&& curl https://nginx.org/download/nginx-$NGINX_VERSION.tar.gz -o $BUILD_ROOT/nginx-$NGINX_VERSION.tar.gz \
&& tar vxzf nginx-$NGINX_VERSION.tar.gz \
&& unzip pcre-$PCRE_VERSION.zip \
&& tar vxfz zlib-$ZLIB_VERSION.tar.gz \
&& tar vxfz openssl-$OPENSSL_VERSION.tar.gz \
&& cd nginx-$NGINX_VERSION \
&& BUILD_CONFIG="\
--prefix=/etc/nginx \
--sbin-path=/usr/sbin/nginx \
--conf-path=/etc/nginx/nginx.conf \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--pid-path=/var/run/nginx.pid \
--lock-path=/var/run/nginx.lock \
--http-client-body-temp-path=/var/cache/nginx/client_temp \
--http-proxy-temp-path=/var/cache/nginx/proxy_temp \
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp \
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp \
--http-scgi-temp-path=/var/cache/nginx/scgi_temp \
--with-openssl=$BUILD_ROOT/openssl-$OPENSSL_VERSION \
--with-pcre=$BUILD_ROOT/pcre-$PCRE_VERSION \
--with-zlib=$BUILD_ROOT/zlib-$ZLIB_VERSION \
--with-http_ssl_module \
--with-http_v2_module \
--with-threads \
&& mkdir -p /var/cache/nginx \
&& ./configure $BUILD_CONFIG \
&& make && make install \
&& rm -rf $BUILD_ROOT \
&& yum -y remove gcc gcc-c++ make perl zip unzip \
&& yum clean all
EXPOSE 80 443
CMD ["nginx", "-g", ""]
.dockerignore
作用与git的.gitignore文件类似。在Dockerfile的同级目录下增加.dockerignore,将不需要传递给docker的文件名配置进去,可以有效减少传递给docker命令的数据,提高构建效率。
文章对.dockerignore的作用和使用方法有比较全面的介绍。
apt-get运行时将在路径/var/lib/apt/lists/缓存数据,因此构建动作完成后,需要手工清理这个路径。
执行apt-get remove清理软件之后,可能存在一些无用的软件,因此不要忘记执行apt-get autoremove。
yum -y在运行时不需要用户确认,所有行为默认用户同意,比较适合在非交互模式比如在Dockerfile这种场景下使用。
yum命令在运行时会在路径/var/cache/yum产生缓存数据,执行yum clean all可以清理这些缓存,释放空间,减少最终镜像占用的空间。
yum update会更新系统,如果基础镜像版本旧的话,可能会下载、***大量的软件,导致最终的镜像占用的空间比较大。
常用的命令
# 删除已停止的容器
sudo docker ps -q -a | xargs sudo docker rm
# 删除无效的镜像
sudo docker rmi $(sudo docker images | grep "^" | awk '{print $3}')
发表在 , ,
2017年十月
9101112131415
16171819202122
23242526272829

参考资料

 

随机推荐