springboot 整合mybatis和redis
2018-09-06 09:24
751 查看
1.pom文件
[code]<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency> </dependencies>
2.配置文件/src/main/resources/application.properties
[code]spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=HlztLhy spring.datasource.driver-class-name=com.mysql.jdbc.Driver mybatis.mapper-locations= classpath:mapper/*.xml mybatis.configuration.cache-enabled=true spring.redis.database=0 #server host spring.redis.host=localhost #server password spring.redis.password= #connection port spring.redis.port=6379
3.RedisTemplate 的 java bean
[code]package com.knife.bootmybatis; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; @Configuration public class RedisConfig { /** * 存入对象序列化信息 * @return */ @Bean public RedisTemplate<String,Object> redisSerizlizerObj(RedisConnectionFactory redisConnectionFactory){ RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); redisTemplate.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 设置值(value)的序列化采用Jackson2JsonRedisSerializer。 redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // 设置键(key)的序列化采用StringRedisSerializer。 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
4.自定义cach类
[code]package com.knife.bootmybatis; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.ibatis.cache.Cache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.util.CollectionUtils; public class MybatisRedisCache implements Cache { private static final Logger logger = LoggerFactory.getLogger(MybatisRedisCache.class); // 读写锁 private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true); private static ApplicationContext applicationContext; private static RedisTemplate<String, Object> redisTemplate; public static ApplicationContext getApplicationContext() { return applicationContext; } public static void setApplicationContext(ApplicationContext applicationContext) { MybatisRedisCache.applicationContext = applicationContext; redisTemplate = SpringContextHolder.getBean("redisTemplate"); } private String id; public MybatisRedisCache(final String id) { if (id == null) { throw new IllegalArgumentException("Cache instances require an ID"); } logger.info("Redis Cache id " + id); this.id = id; } @Override public String getId() { return this.id; } @Override public void putObject(Object key, Object value) { if (value != null) { // 向Redis中添加数据,有效时间是2天 redisTemplate.opsForValue().set(key.toString(), value, 2, TimeUnit.DAYS); } } @Override public Object getObject(Object key) { try { if (key != null) { Object obj = redisTemplate.opsForValue().get(key.toString()); return obj; } } catch (Exception e) { logger.error("redis "); } return null; } @Override public Object removeObject(Object key) { try { if (key != null) { redisTemplate.delete(key.toString()); } } catch (Exception e) { } return null; } @Override public void clear() { logger.debug("清空缓存"); try { Set<String> keys = redisTemplate.keys("*:" + this.id + "*"); if (!CollectionUtils.isEmpty(keys)) { redisTemplate.delete(keys); } } catch (Exception e) { } } @Override public int getSize() { Long size = (Long) redisTemplate.execute(new RedisCallback<Long>() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { return connection.dbSize(); } }); return size.intValue(); } @Override public ReadWriteLock getReadWriteLock() { return this.readWriteLock; } }
5.模型 要实现Serializable
[code]package com.knife.bootmybatis; import java.io.Serializable; public class User implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private int id; private String name; private String pw; private int state; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPw() { return pw; } public void setPw(String pw) { this.pw = pw; } public int getState() { return state; } public void setState(int state) { this.state = state; } public String toString() { return "id:" + id + " name:" + name; } }
6.mapper
[code]package com.knife.bootmybatis; import java.util.List; import org.apache.ibatis.annotations.Mapper; @Mapper public interface UserMapper { public List<User> all(); }
[code]<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.knife.bootmybatis.UserMapper"> <cache type="com.knife.bootmybatis.MybatisRedisCache" /> <select id="all" resultType="com.knife.bootmybatis.User"> <![CDATA[ select * from user ]]> </select> </mapper>
7.初始化
[code]package com.knife.bootmybatis; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { MybatisRedisCache.setApplicationContext(SpringApplication.run(App.class, args)); } }
8.测试接口
[code]package com.knife.bootmybatis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class C { @Autowired private UserMapper dao; @RequestMapping("list") @ResponseBody public Object getUser(){ return dao.all(); } }
9.结果
访问测试接口
查看redis
阅读更多
相关文章推荐
- SpringBoot整合常用技术--MyBatis、Redis、定时任务、分页插件、逆向生成
- SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例
- springboot mybatis整合redis
- Spring Boot + MyBatis + Redis整合小案例
- SpringCloud SpringBoot mybatis 分布式微服务(二十四)整合Redis
- SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例(转)
- SpringBoot+Redis+Mybatis+AngularJS整合开发
- SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例
- spring boot 整合mybatis,redis,热部署
- SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例
- spring boot 整合mybatis、redis、 spring mvc基本配置
- SpringBoot整合mybatis、shiro、redis实现基于数据库的细粒度动态权限管理系统实例
- Java爬虫初体验:简单抓取IT之家热评(整合Spring Boot+Elasticsearch+Redis+Mybatis)
- 企业分布式微服务云SpringCloud SpringBoot mybatis (十三)Spring Boot整合MyBatis
- spring boot 下 shiro+redis与mybatis redis cache冲突的解决办法
- springboot整合mybatis中的坑
- SpringBoot整合Redis
- spring boot 整合redis对查询数据做缓存( 利用spring的AOP技术)
- SpringBoot整合MyBatis
- spring boot +springMVC +mybatis整合踩过的坑