搭建springboot+mybatis
maven依赖
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<!-- 排除默认的redis客户端lettuce -->
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 引入redis客户端jedis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
</dependencies>
application.yml
spring:
#DataSource
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/shop?charset=utf8mb4&useSSL=false&serverTimezone=UTC
username: root
password: root
#Hikari 数据源专用配置
hikari:
maximum-pool-size: 20
minimum-idle: 5
#Data-Rides
redis:
jedis:
pool:
min-idle: 5
max-active: 10
max-idle: 10
max-wait: 2000
port: 6379
host: 127.0.0.1
timeout: 1000
#spring cache
cache:
type: redis
cache-names: redisCache
#mybatis
mybatis:
type-aliases-package: com.java.xrc.entity
mapper-locations: classpath:mappers/*.xml
Entity
@Alias("student")
public class Student implements Serializable {
private Integer id;
private String name;
private String serial;
//get set...
}
mapper
@Mapper
public interface StudentMapper {
Optional<Student> getById(@Param("id") Integer id);
}
<?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.java.xrc.dao.StudentMapper">
<select id="getById" parameterType="int" resultType="student">
select id,name,serial from student where id=#{id}
</select>
</mapper>
使用spring缓存注解操作redis
开启redis,写入application.yml中redis相关配置。
在service中使用注解:
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
@Cacheable(value = "redisCache", key="'student_'+#id")
public Optional<Student> getById(Integer id) {
return studentMapper.getById(id);
}
}
在启动类中开启spring缓存
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
在redis客户端输入keys * 可以查看缓存是否成功。
127.0.0.1:6379> keys *
1) "redisCache::student_2"
Spring缓存注解
@CachePut
表示将方法结果返回存放到缓存中,常用于插入和更新方法上。
@Cacheable
表示先从缓存中通过定义的键查询,如果可以查询到数据,则返回,否则执行该方法,返回数据,并且将结果保存到缓存中,常用于查询方法上。
@CacheEvict
通过定义键移除缓存,常用户删除方法上。
自定义缓存管理器
我们也可以通过注入RedisCacheManger的bean,来使用自定义的缓存管理器。
@Configuration
public class RedisCacheConfig {
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Bean
public RedisCacheManager redisCacheManager(){
//redis加锁写入器
RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(redisConnectionFactory);
//启动redis缓存的默认设置
RedisCacheConfiguration config= RedisCacheConfiguration.defaultCacheConfig()
//设置JDK序列化器
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new JdkSerializationRedisSerializer()))
//禁用前缀
.disableKeyPrefix()
//设置有效时长1分钟
.entryTtl(Duration.ofMinutes(1));
//创建redis缓存管理器
RedisCacheManager redisCacheManager=new RedisCacheManager(writer,config);
return redisCacheManager;
}
}
使用RedisTemplate操作redis
spring-boot-starter-data-redis 也为spring注入了redis的操作类RedisTemplate、StringRedisTemplate等,使用这些类也可以操作redis。上面的service类也可以改为:
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Autowired
private RedisTemplate redisTemplate;
@Override
public Optional<Student> getById(Integer id) {
String reidsKey = "redisCache::student_" + id;
//判断缓存中是否存在该值
if (redisTemplate.hasKey(reidsKey)) {//存在则从内存中读取并返回
Student student = (Student) redisTemplate.opsForValue().get(reidsKey);
return Optional.of(student);
} else {//不存在则从数据库查询出,写入内存并返回。
Optional<Student> optional = studentMapper.getById(id);
if (optional.isPresent()) {
redisTemplate.opsForValue().set(reidsKey, optional.get());
return optional;
} else return Optional.empty();
}
}
}