一.整合Druid数据源

  Druid是一个关系型数据库连接池,是阿里巴巴的一个开源项目,Druid在监控,可扩展性,稳定性和性能方面具有比较明显的优势.通过Druid提供的监控功能,可以实时观察数据库连接池和SQL查询的工作情况.使用Druid在一定程度上可以提高数据库的访问技能.

  1.1 在pom.xml中添加依赖

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.18</version>
</dependency>

  1.2 Druid数据源配置

  在application.properties中,去书写Druid数据源的配置信息.

##Druid##
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
spring.datasource.useGlobalDataSourceStat=true

  1.3 建立DruidConfiguration配置类,配置过滤信息

@Configuration
public class DruidConfiguration {
@Bean
public ServletRegistrationBean statViewServle(){
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
//白名单:
servletRegistrationBean.addInitParameter("allow","192.168.1.218,127.0.0.1");
//IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的即提示:Sorry, you are not permitted to view this page.
servletRegistrationBean.addInitParameter("deny","192.168.1.100");
//登录查看信息的账号密码.
servletRegistrationBean.addInitParameter("loginUsername","druid");
servletRegistrationBean.addInitParameter("loginPassword","12345678");
//是否能够重置数据.
servletRegistrationBean.addInitParameter("resetEnable","false");
return servletRegistrationBean;
} @Bean
public FilterRegistrationBean statFilter(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
//添加过滤规则.
filterRegistrationBean.addUrlPatterns("/*");
//添加不需要忽略的格式信息.
filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
}

  1.4 配置数据源的信息

  告诉springboot采用Druid数据源:

 @Bean(name = "dataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource(){
return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
}

  接下来就可以通过localhost:8080/druid/index.html去打开控制台,观察过滤信息了!

二.使用@Cache简化redis配置

  在实体类比较简单的时候(例如:没有一对多,多对多这类复杂的关系,不是List,Map这类数据类型,只是一个Pojo类),可以使用@Cache去替代书写BeanRedis注入RedisTemplate的方式去访问Redis数据库.

  2.1 建立RoleService.采用@Cacheable和@CachePut去访问Redis

  实体类的主要属性如下:

@Service
public class RoleService {
@Autowired
private RoleRepository roleRepository;
@Autowired
private RoleRedis roleRedis; @Cacheable(value = "mysql:findById:role", keyGenerator = "simpleKey")
public Role findById(Long id) {
System.out.println("从数据库中查询");
return roleRepository.findOne(id);
} @CachePut(value = "mysql:findById:role", keyGenerator = "objectId")
public Role create(Role role) {
System.out.println("************在数据库中创建************");
return roleRepository.save(role);
}
//简单的操作使用注解的形式
@CachePut(value = "mysql:findById:role", keyGenerator = "objectId")
public Role update(Role role) {
System.out.println("************在数据库中更新************");
return roleRepository.save(role);
} @CacheEvict(value = "mysql:findById:role", keyGenerator = "simpleKey")
public void delete(Long id) {
System.out.println("************在数据库中销毁************");
roleRepository.delete(id);
} public List<Role> findAll(){
List<Role> roleList = roleRedis.getList("mysql:findAll:role");
if(roleList == null) {
roleList = roleRepository.findAll();
if(roleList != null)
roleRedis.add("mysql:findAll:role", 5L, roleList);
}
return roleList;
}
//复杂的依然使用RedisTemplate的形式
public Page<Role> findPage(RoleQo roleQo){
Pageable pageable = new PageRequest(roleQo.getPage(), roleQo.getSize(), new Sort(Sort.Direction.ASC, "id")); PredicateBuilder pb = new PredicateBuilder(); if (!StringUtils.isEmpty(roleQo.getName())) {
pb.add("name","%" + roleQo.getName() + "%", LinkEnum.LIKE);
} Page<Role> pages = roleRepository.findAll(pb.build(), Operator.AND, pageable);
return pages;
} }

 注意,@Cacheable放置于方法上,当调用这个方法时,程序会先根据key(value加上KeyGenerator生成的key)去寻找有没有对应的对象结果,如果有的话,直接返回,没有才执行方法(从数据库找).而@CachePut则会更新Redis缓存,同时执行对应的方法.@CacheEvict会删除Redis缓存对应的对象. 

 2.2 建立Redis配置类,需要去配置Redis的注解

@ConfigurationProperties("application.properties")
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport { @Value("${spring.redis.hostName}")
private String hostName;
@Value("${spring.redis.port}")
private Integer port; @Bean
public RedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory cf = new JedisConnectionFactory();
cf.setHostName(hostName);
cf.setPort(port);
cf.afterPropertiesSet();
return cf;
}
//配置key的生成
@Bean
public KeyGenerator simpleKey(){
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName()+":");
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
//配置key的生成
@Bean
public KeyGenerator objectId(){
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params){
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName()+":");
try {
sb.append(params[0].getClass().getMethod("getId", null).invoke(params[0], null).toString());
}catch (NoSuchMethodException no){
no.printStackTrace();
}catch(IllegalAccessException il){
il.printStackTrace();
}catch(InvocationTargetException iv){
iv.printStackTrace();
}
return sb.toString();
}
};
}
//配置注解
@Bean
public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
RedisCacheManager manager = new RedisCacheManager(redisTemplate);
manager.setDefaultExpiration(43200);//12小时
return manager;
}
//对于复杂的属性仍然使用RedisTemplate
@Bean
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();
return template;
} }

  2.3 测试

springboot学习笔记-4 整合Druid数据源和使用@Cache简化redis配置的更多相关文章

  1. springboot学习笔记-3 整合redis&mongodb

    一.整合redis 1.1 建立实体类 @Entity @Table(name="user") public class User implements Serializable ...

  2. springboot学习笔记:7.IDEA下5步完成热部署配置

    开发工具IDEA 2017.02   JDK1.8 1.pom.xml中增加: <dependency> <groupId>org.springframework.boot&l ...

  3. Spring Boot 学习笔记(六) 整合 RESTful 参数传递

    Spring Boot 学习笔记 源码地址 Spring Boot 学习笔记(一) hello world Spring Boot 学习笔记(二) 整合 log4j2 Spring Boot 学习笔记 ...

  4. SpringBoot整合Druid数据连接池

    SpringBoot整合Druid数据连接池 Druid是什么? Druid是Alibaba开源的的数据库连接池.Druid能够提供强大的监控和扩展功能. 在哪里下载druid maven中央仓库: ...

  5. SpringBoot学习笔记(7):Druid使用心得

    SpringBoot学习笔记(7):Druid使用心得 快速开始 添加依赖 <dependency> <groupId>com.alibaba</groupId> ...

  6. SpringBoot学习笔记(10):使用MongoDB来访问数据

    SpringBoot学习笔记(10):使用MongoDB来访问数据 快速开始 本指南将引导您完成使用Spring Data MongoDB构建应用程序的过程,该应用程序将数据存储在MongoDB(基于 ...

  7. Springboot学习07-数据源Druid

    Springboot学习07-数据源Druid 关键字 Druid 前言 学习笔记 正文 1-Druid是什么 Druid是阿里巴巴开源平台上的一个项目,整个项目由数据库连接池.插件框架和SQL解析器 ...

  8. springboot学习笔记:9.springboot+mybatis+通用mapper+多数据源

    本文承接上一篇文章:springboot学习笔记:8. springboot+druid+mysql+mybatis+通用mapper+pagehelper+mybatis-generator+fre ...

  9. SpringBoot学习笔记(14):使用SpringBootAdmin管理监控你的应用

    SpringBoot学习笔记(14):使用SpringBootAdmin管理监控你的应用 Spring Boot Admin是一个管理和监控Spring Boot应用程序的应用程序.本文参考文档: 官 ...

随机推荐

  1. Python之matplotlib模块安装

    numpy 1.下载安装 源代码 http://sourceforge.net/projects/numpy/files/NumPy/ 安装 python2.7 setup.py install 2. ...

  2. pandas选择数据-【老鱼学pandas】

    选择列 根据列名来选择某列的数据 import pandas as pd import numpy as np dates = pd.date_range("2017-01-08" ...

  3. 《Metasploit魔鬼训练营》第七章学习笔记

    P314 木马程序的制作 msfpayload和msfencoder已被msfvenom取代.使用msfvenom -h查看具体用法.以下网址也有相关教程: https://github.com/ra ...

  4. laravel 500错误的一个解决办法

    我从svn上update下来了开发环境的目录,结果当我访问本地的根目录的时候却报了500错误,百度了许多,也看了很多博客,发现都没有解决我的问题,所以我觉得我的解决办法值得一写,当你从svn上upda ...

  5. React服务器端渲染值Next.js

    昨天leader给分配了新任务,让熟悉一下ssr,刚开始有点懵,啥玩意?百度了一下,不就是服务器端渲染(server side render,简称: ssr). ssr简介 服务端渲染一个很常见的场景 ...

  6. 邻里街坊 golang入坑系列

    如果要追新或者怀旧,就点击https://andy-zhangtao.gitbooks.io/golang/content/ . 博客园里面的文章基本和gitbook上面是保持同步的. 这几天看了几集 ...

  7. 物联网蓝牙模块:DA14586蓝牙5模块很快到来

    Dialog半导体的SmartBond系列的下一代产品---DA14586已经发布.该全新的系统级芯片(SoC)是公司首款支持最新蓝牙5.0规范的独立器件,为先进应用提供最低的功耗和无可比拟的功能. ...

  8. Linux系统bash shell之历史命令

    1.相关变量: HISTSIZE: 定义命令历史记录的条数 HISTFILE: 定义命令储存的文件,一般是 ~/.bash_history HISTFILESIZE: 定义了历史文件记录历史的条数 H ...

  9. chromium源码阅读--HTTP Cache

    最近积累了一些关于HTTP缓存的知识,因此结合Chromium的实现总结一下,主要从如下2个分面: 1.HTTP缓存的基础知识 2.Chromium关于HTTP缓存的实现分析 一.HTTP缓存的基础知 ...

  10. Vue单页面骨架屏实践

    github 地址: VV-UI/VV-UI 演示地址: vv-ui 文档地址:skeleton 关于骨架屏介绍 骨架屏的作用主要是在网络请求较慢时,提供基础占位,当数据加载完成,恢复数据展示.这样给 ...