创立我的项目
第一步当然是创立一个springBoot我的项目,并导入依赖嘛。这就不多说了。
这儿咱们就不必jedis了,spring对redis也有反对,咱们就用spring-boot-starter-data-redis来整合redis。
<!--https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.3.5.RELEASE</version></dependency>
写配置
spring: #redis 的配置 redis: host: localhost port: 6379 database: 0# 数据源,我用了druid datasource: type: com.alibaba.druid.pool.DruidDataSource password: 12345678 username: root url: jdbc:mysql://localhost:3306/redis?characterEncoding=UTF-8 druid: stat-view-servlet: url-pattern: /druid/* login-password: 123456 login-username: admin#mybatis 的配置mybatis: mapper-locations: classpath:/mapper/*.xml# 配置日志打印logging: level: com.tao.redis_demo_springboot.dao: debug
## 环境
咱们来搭建根本的一个增删该查
咱们新建一个测试类,来测试一下
那咱们该如何让redis进行缓存呢?
在mybatis中,咱们能够通过cache标签来开启二级缓存,这个默认的缓存是org.apache.ibatis.cache.impl.PerpetualCache
来实现的。
在cache标签中,type能够指定缓存类。那咱们能够自定义一个缓存类,用springboot提供的redistemplate 来对redis进行操作。也就是说,咱们通过这个自定义的缓存类来操作redis,咱们也就胜利地用redis来做缓存了。
自定义缓存类
那咱们如何来定义一个缓存类呢?
咱们能够看看mybatis他是如何实现的,咱们能够照猫画虎,去看看PerpetualCache
的源码。
public class PerpetualCache implements Cache { private final String id; private final Map<Object, Object> cache = new HashMap<>(); public PerpetualCache(String id) { this.id = id; } @Override public String getId() { return id; } @Override public int getSize() { return cache.size(); } @Override public void putObject(Object key, Object value) { cache.put(key, value); } @Override public Object getObject(Object key) { return cache.get(key); } @Override public Object removeObject(Object key) { return cache.remove(key); } @Override public void clear() { cache.clear(); } @Override public boolean equals(Object o) { if (getId() == null) { throw new CacheException("Cache instances require an ID."); } if (this == o) { return true; } if (!(o instanceof Cache)) { return false; } Cache otherCache = (Cache) o; return getId().equals(otherCache.getId()); } @Override public int hashCode() { if (getId() == null) { throw new CacheException("Cache instances require an ID."); } return getId().hashCode(); }}
一看源码就很清晰了,他是用一个map来治理缓存。那能够把缓存在redis中也写成一个map的格局。