一.整合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# 读写文本文件乱码解决方案

    在使用C#对文本文件读取的时候,如果其中包含了中文,经常会出现乱码.一般解决是在StreamReader加一个编码,我使用的是Encoding.UTF8,一般情况下使用这个参数就可以.但是,在这次我使 ...

  2. 10个鲜为人知的C#关键字

    在正式开始之前,我需要先声明:这些关键字对于偏向底层的程序员更加耳熟能详,对这些关键字不了解并不影响你作为一个合格的程序员. 这意味着这些关键字会让你在编写程序时得到更好的代码质量和可读性,enjoy ...

  3. JavaScript基本知识点整理(超实用)

      絮叨絮叨                   今天给大家分享一下这两天自己整理的JavaScript部分的笔记,下面都是我觉得比较常用的,希望能帮助到大家! 1. 导入JS的三种方式 ①在HTML ...

  4. 使用MongoVUE

    mongoDB版本号为3.4.10 在终端操作一顿后想看看它在可视化工具里面什么样子,于是就找了一个可视化工具,MongoVUE这个看起来还不错,因为我是windows系统所以就没有太多的挑选选择.在 ...

  5. 关于回调(callback)

    如果要理解回调,需要在分同步通信.异步通信的基础上了解 举个通俗的例子: 你打电话问书店老板有没有<JS>这本书,如果是同步通信机制,书店老板会说,你稍等,"我查一下" ...

  6. Foundation框架的小总结

    一.Foundation框架—结构体 一.基本知识 Foundation框架中包含了很多开发中常用的数据类型,如结构体,枚举,类等,是其他ios框架的基础. 如果要想使用foundation框架中的数 ...

  7. 项目实战6—Mysql实现企业级日志管理、备份与恢复实战

    Mysql实现企业级日志管理.备份与恢复实战 环境背景:随着业务的发展,公司业务和规模不断扩大,网站积累了大量的用户信息和数据,对于一家互联网公司来说,用户和业务数据是根基.一旦公司的数据错乱或者丢失 ...

  8. Android Weekly Notes Issue #286

    December 3rd, 2017 Android Weekly Issue #286 本期文章包含如何通过踩坑来学习Kotlin,以及利用Kotlin的data class做MVVM状态保存,还包 ...

  9. eclipse和myeclipse中将项目发布到tomcat的root目录

    1.在eclipse中,将项目直接部署在tomcat的root目录中,这样便可以直接ip:port访问项目: 项目右键->属性->web project settings 添加之后直接启动 ...

  10. Linux下SVN安装配置以及使用

    第一章 安装 1. 采用源文件编译安装.源文件共两个,为: subversion-1.6.21.tar.gz(subversion 源文件) subversion-deps-1.6.21.tar.gz ...