一.整合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. c# asp.net 多数组索引的解决方法

    本人今天做了一个功能 需要在一个类里用多个数组, 数组需要索引器来调用  一个数组 我查了msdn 一个类里面只能有一个this 索引器 那这么多数组如何构造索引呢 我在坛子里找到了解决之道 view ...

  2. 微信小程序的网络设置,及网络请求:wx.request(OBJECT)

    Md2All 一个Markdown在线转换工具 网址:http://md.aclickall.com 微信公众号:颜家大少本文所用排版工具:http://md.aclickall.com 支持通用的M ...

  3. 圆形的ImageView

    转载自gitHub的ImageView,因为本身就是可用的,也没什么好说的,拷贝回去用就是了,可以设置除了背景,还可以设置边框什么的,比起CardView设置圆角,功能更加强大. import and ...

  4. APP加固技术历程及未来级别方案:虚机源码保护

    传统App加固技术,前后经历了四代技术变更,保护级别每一代都有所提升,但其固有的安全缺陷和兼容性问题始终未能得到解决.而下一代加固技术-虚机源码保护,适用代码类型更广泛,App保护级别更高,兼容性更强 ...

  5. Less的内置函数

    杂项函数 color 解析颜色,将代表颜色的字符串转换为颜色值. 参数: string: 代表颜色值的字符串. 返回值: color 案例: color("#aaa"); 输出: ...

  6. 从Proxy.newInstance出发

    写在前面 本篇博客是基于对动态代理,java的重写,多态特性了解的基础上对于源码的阅读,先提出几个问题 1.从静态代理变成动态代理需要解决两个问题,如何动态实现被代理类的接口并摘取接口中的方法,如果动 ...

  7. 【原创】python实现清理本地缓存垃圾

    #coding=utf-8 import os import glob try: #利用glob模块定位需要清理垃圾的模糊路径 File_1 = glob.glob("C:\Windows\ ...

  8. Java数据结构和算法(五)——队列

    前面一篇博客我们讲解了并不像数组一样完全作为存储数据功能,而是作为构思算法的辅助工具的数据结构——栈,本篇博客我们介绍另外一个这样的工具——队列.栈是后进先出,而队列刚好相反,是先进先出. 1.队列的 ...

  9. VC++下编译 程序“减肥”

    在vc6 和 vs 2008下 编译 以下代码,不更改任何编译设置(vc6  40k , s2008 7k). 一.vc6下,Release 模式 编译处理. 1.去掉不必要的 链接库  工程(Pro ...

  10. codeup模拟赛 进击的二叉查找数

    问题 B: 进击的二叉查找树 时间限制: 1 Sec 内存限制: 64 MB 提交: 1017 解决: 379 提交状态 题目描述 给定1~N的两个排列,使用这两个排列分别构建两棵二叉查找树(也就是通 ...