关于redis:集成Redismybatisspringboot

4次阅读

共计 2030 个字符,预计需要花费 6 分钟才能阅读完成。

创立我的项目

第一步当然是创立一个 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 的格局。

正文完
 0