spring boot 整合常用框架
详情可看官方文档:https://docs.spring.io/spring-boot/docs/2.0.2.RELEASE/reference/htmlsingle
-
整合数据源
-
添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
-
编写配置文件
type: 数据源类型,指定你使用的时那个数据源。缺省情况下spring boot 首选Hikari,如果Hikari不可用将会选择tomcat,在两者都不可以而dbcp2可用,将会选择dbcp2
initial-size: 连接池初始化时创建的连接数
min-idle: 池中始终保持的最小连接数
max-active: 可创建的最大连接数
max-wait: 最大等待时间(毫秒),如果获取连接的时间超过此时间,抛出异常
time-between-eviction-runs-millis: 空闲连接回收线程的休眠时间
min-evictable-idle-time-millis: 空闲线程的最小存活时间,一个线程的空闲时间超过此时间,将会在空闲连接回收线程启动时被回收
validation-query: 在连接池返回给调用者连接时,用来验证连接是否可用的sql语句
test-while-idle:是否在连接空闲一段时间后检测其可用性
test-on-borrow:当从池中获取一个连接时,是否验证,验证失败会删除连接并尝试获取新的连接
test-on-return: 当一个连接归还连接池时,是否进行验证
pool-prepared-statements: 是否使用 prepared statements
max-pool-prepared-statement-per-connection-size: 每个prepared statements连接的最大大小
spring: datasource: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/testdata username: root password: root initial-size: 5 min-idle: 5 max-active: 30 max-wait: 30000 time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 300000 validation-query: SELECT 1 FROM DUAL test-while-idle: true test-on-borrow: false test-on-return: false pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20
-
使用Druid
加入Druid依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.9</version> </dependency>
修改配置文件
将数据源类型改为 com.alibaba.druid.pool.DruidDataSource
filters:配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall’用于防火墙
use-global-data-source-stat: 合并多个DruidDataSource的监控数据
connection-properties: 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring: datasource: type: com.alibaba.druid.pool.DruidDataSource filters: stat,wall,log4j use-global-data-source-stat: true connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
自定义数据源配置类
想要使用其他的数据源,需要对数据源的配置类进行自定义编写
@Configuration public class DruidConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource") public DruidDataSource getDruidDataSource() { return new DruidDataSource(); } @Bean public ServletRegistrationBean statViewServlet() { ServletRegistrationBean bean; bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); HashMap<Object, Object> initParams = new HashMap<>(); initParams.put("loginUsername", "root"); //账号 initParams.put("loginPassword", "root"); //密码 initParams.put("allow", "127.0.0.1"); //允许访问IP initParams.put("deny", ""); //禁止访问iP bean.setInitParameters(initParams); return bean; } /** * 配置一个web监控的Filter * * @return */ @Bean public FilterRegistrationBean webStatFilter() { FilterRegistrationBean bean; bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); HashMap<Object, Object> initParams = new HashMap<>(); initParams.put("exclusions", "*.js,*.css,/druid/*"); bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList("/*")); return bean; } }
访问 http://127.0.0.1:8080/druid 查看数据源和sql的执行情况
-
-
整合mybatis
-
添加依赖
依赖是由mybatis官方提供的,而不是Sping boot 提供。
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency>
-
声明mapper类
方式一: 使用@Mapper注解
@Mapper public interface EmpMapper { void insert(EmpDo empDo); void deleteByPrimaryKey(int id); void updateByPrimaryKeySelective(EmpDo empDo); EmpDo getEmp(int id); List<EmpDo> listAllEmp(); }
方式二: 使用@MapperScan注解进行包扫描
@SpringBootApplication @MapperScan("pers.jaye.springbootdemo.mapper") public class SpringBootDemoApplication { public static void main(String[] args) { SpringApplication.run(SpringBootDemoApplication.class, args); } }
-
注解式开发
直接使用注解在mapper接口方法上进行sql编写
@Mapper public interface DeptMapper { @Options(useGeneratedKeys = true, keyProperty = "dno") @Insert("insert into dept (dno,dname,loc) values (#{dno},#{dname},#{loc})") void insert(DeptDo deptDo); @Delete("delect from dept where dno = #{dno}") void delect(int dno); @Update("update dept set dname = #{dname} , loc = #{loc} where dno = #{dno}") void update(DeptDo deptDo); @Select("select dno,dname,loc from dept where dno = #{dno}") DeptDo getEmp(int dno); @Select("select dno,dname,loc from dept") List<DeptDo> listAllEmps(); }
@RunWith(SpringRunner.class) @SpringBootTest public class SpringBootDemoApplicationTests { @Resource private DeptMapper deptMapper; @Test public void mybatisTest() { List<DeptDo> deptDos = deptMapper.listAllDepts(); Assert.assertTrue(deptDos.size() == 34); } }
-
xml式开发
在核心配置文件中配置mybatis
#sql-xml文件目录 mybatis: mapper-locations: classpath:sql/*.xml
编写sql-xml
<mapper namespace="pers.jaye.springbootdemo.mapper.EmpMapper"> <resultMap id="BaseResultMap" type="pers.jaye.springbootdemo.model.EmpDo"> <result column="eid" property="eid"/> <result column="ename" property="ename"/> <result column="job" property="job"/> <result column="deptno" property="deptno"/> </resultMap> <sql id="Base_Column_List"> eid,ename,job,deptno </sql> <select id="listAllEmp" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from emp </select> </mapper>
测试
@RunWith(SpringRunner.class) @SpringBootTest public class SpringBootDemoApplicationTests { @Resource private EmpMapper empMapper; @Test public void mybatisTest() { List<EmpDo> empDos = empMapper.listAllEmp(); Assert.assertTrue(empDos.size() == 800000); } }
-
-
整合redis
-
添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
-
在核心配置文件中配置redis
database : 使用哪个redis库 默认为0
timeout: 一个请求最长持有一个连接的时间
min-idle: 最小空闲连接
max-idle: 最大空闲连接
max-active: 池中最多存活的连接数
max-wait: 请求获取连接最大等待时间
spring: redis: database: 0 host: 192.168.1.205 port: 6379 password: timeout: 30000 jedis: pool: min-idle: 5 max-idle: 8 max-active: 30 max-wait: 30000
-
继承CachingConfigurerSupport编写自己的缓存配置类
@EnableCaching 启用缓存, 扫描拦截所有带有 @Cacheable,@CacheEvict 等注解的方法
@Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { /** * 自定义 CacheManager - 指定使用 RedisCacheManager * @param factory * @return */ @Bean public CacheManager cacheManager(RedisConnectionFactory factory) { RedisSerializer<String> redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); // 配置序列化 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig(); RedisSerializationContext.SerializationPair<String> keySerializationPair = RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer); RedisSerializationContext.SerializationPair valueSerializationPair = RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer); RedisCacheConfiguration redisCacheConfiguration = config.serializeKeysWith(keySerializationPair).serializeValuesWith(valueSerializationPair); RedisCacheManager redisCacheManager = RedisCacheManager.builder(factory).cacheDefaults(redisCacheConfiguration).build(); return redisCacheManager; } /** * 自定义redis的Key规则 * @return */ @Bean public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } }
-
使用redis
第一次请求UserService的listAllUser方法时,查询mysql数据库获取数据。第二次调用此方法时,并没有去查询mysql数据库。证明redis有效
@Service @CacheConfig(cacheNames = "User") public class UserService { @Resource private UserMapper userMapper; @CacheEvict(allEntries = true) public void insertUser(UserDo userDo) { userMapper.insertUser(userDo); } @Cacheable public List<UserDo> listAllUser() { return userMapper.listAllUser(); } }
@RunWith(SpringRunner.class) @SpringBootTest public class SpringBootDemoApplicationTests { @Resource private UserService userService; @Test public void redisTest(){ List<UserDo> userDos = userService.listAllUser(); System.out.printf(userDos.toString()); } }
-
-
整合springmvc
spring boot 完美集成了springmvc,你不需要进行任何的配置就可以去使用它。
如何你想详细的了解它可以查看官方文档:https://docs.spring.io/spring-boot/docs/2.0.2.RELEASE/reference/htmlsingle/#howto-spring-mvc
-
整合shiro
-
整合thymeleaf