springboot学习笔记-4 整合Druid数据源和使用@Cache简化redis配置
一.整合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配置的更多相关文章
- springboot学习笔记-3 整合redis&mongodb
一.整合redis 1.1 建立实体类 @Entity @Table(name="user") public class User implements Serializable ...
- springboot学习笔记:7.IDEA下5步完成热部署配置
开发工具IDEA 2017.02 JDK1.8 1.pom.xml中增加: <dependency> <groupId>org.springframework.boot&l ...
- Spring Boot 学习笔记(六) 整合 RESTful 参数传递
Spring Boot 学习笔记 源码地址 Spring Boot 学习笔记(一) hello world Spring Boot 学习笔记(二) 整合 log4j2 Spring Boot 学习笔记 ...
- SpringBoot整合Druid数据连接池
SpringBoot整合Druid数据连接池 Druid是什么? Druid是Alibaba开源的的数据库连接池.Druid能够提供强大的监控和扩展功能. 在哪里下载druid maven中央仓库: ...
- SpringBoot学习笔记(7):Druid使用心得
SpringBoot学习笔记(7):Druid使用心得 快速开始 添加依赖 <dependency> <groupId>com.alibaba</groupId> ...
- SpringBoot学习笔记(10):使用MongoDB来访问数据
SpringBoot学习笔记(10):使用MongoDB来访问数据 快速开始 本指南将引导您完成使用Spring Data MongoDB构建应用程序的过程,该应用程序将数据存储在MongoDB(基于 ...
- Springboot学习07-数据源Druid
Springboot学习07-数据源Druid 关键字 Druid 前言 学习笔记 正文 1-Druid是什么 Druid是阿里巴巴开源平台上的一个项目,整个项目由数据库连接池.插件框架和SQL解析器 ...
- springboot学习笔记:9.springboot+mybatis+通用mapper+多数据源
本文承接上一篇文章:springboot学习笔记:8. springboot+druid+mysql+mybatis+通用mapper+pagehelper+mybatis-generator+fre ...
- SpringBoot学习笔记(14):使用SpringBootAdmin管理监控你的应用
SpringBoot学习笔记(14):使用SpringBootAdmin管理监控你的应用 Spring Boot Admin是一个管理和监控Spring Boot应用程序的应用程序.本文参考文档: 官 ...
随机推荐
- 自己动手写Redis客户端(C#实现)4 - 整数回复
整数回复 整数回复就是一个以 ":" 开头, CRLF 结尾的字符串表示的整数. 比如说, ":0\r\n" 和 ":1000\r\n" 都 ...
- pku夏令营面试
北大面试题目: 一.内存交换 内存交换(对换)的基本思想是,把处于等待状态(或在CPU调度原则下被剥夺运行权利) 的程序从内存移到辅存,把内存空间腾出来,这一过程又叫换出:把准备好竞争CPU运行的程序 ...
- python并发编程之多进程一
一,什么是进程 进程是操作系统结构的基础:是一个正在执行的程序:计算机中正在运行的程序实例:可以分配给处理器并由处理器执行的一个实体: 二,进程与程序的区别 进程即运行中的程序,从中即可知,进程是在运 ...
- Logistic 回归模型 第一遍阅读笔记
MLE :最大似然估计,求得的这套参数估计能够通过指定模型以最大概率在线样本观测数据 必须来自随机样本,自变量与因变量之间是线性关系 logistic 回归没有关于自变量分布的假设条件,自变量可以连续 ...
- python中的“.T”操作
其实就是对一个矩阵的转置 看代码: a array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) a.T array([[1, 4, 7], [2, 5, 8], [3, 6, ...
- 老男孩Python视频教程:第一周
认识和尝试Python 备注:老男孩Python视频教程,视频来自网络,在此分享,侵删 对我来说,第一周视频主要解答了以下疑问: 1. Python的三大特点是什么? 答:解释型.动态类型(运行期间才 ...
- 计算机网络初探(ip协议)
粗读了两遍计算机网络(谢希仁),对于计算计算机网络算是有了一个初步的了解,所以打算写一篇文章(希望是教程)进行巩固(主要围绕IP协议). 局域网 因特网的产生和广泛使用极大地改变了我们的生活,但对于不 ...
- POJ1837--二维背包
Balance Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 13525 Accepted: 8474 Description ...
- 大白话Vue源码系列(01):万事开头难
阅读目录 Vue 的源码目录结构 预备知识 先捡软的捏 Angular 是 Google 亲儿子,React 是 Facebook 小正太,那咱为啥偏偏选择了 Vue 下手,一句话,Vue 是咱见过的 ...
- tolua++实现lua层调用c++技术分析
tolua++技术分析 cocos2dx+lua 前言 一直都使用 cocos2dx + lua 进行游戏开发,用 Lua 开发可以专注于游戏逻辑的实现,另外一方面可以实现热更新:而且 lua 是一个 ...