SpringBoot_MyBatis_Redis
一、組件介紹【可用直接連接Redis、并使用Redis和dao層數據緩存】
二、引入依賴
SpringBoot DevTools、SpringData Redis、MyBatis Framework、MySQL Driver、SpringWeb、下面的pool2需要額外導入
<!--Spring Boot 提供了對 Redis 集成的組件包:spring-boot-starter-data-redis,spring-boot-starter-data-redis依賴于spring-data-redis 和 lettuce 。Spring Boot 1.0 默認使用的是 Jedis 客戶端,2.0 替換成 Lettuce。
Lettuce 是一個可伸縮線程安全的 Redis 客戶端,多個線程可以共享同一個 RedisConnection,它利用優秀 netty NIO 框架來高效地管理多個連接。-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
三、添加application.properties配置
# Redis數據庫索引(默認為0)
spring.redis.database=0
# Redis服務器地址
spring.redis.host=localhost
# Redis服務器連接端口
spring.redis.port=6379
# Redis服務器連接密碼(默認為空)
spring.redis.password=
# 連接池最大連接數(使用負值表示沒有限制) 默認 8
spring.redis.lettuce.pool.max-active=8
# 連接池最大阻塞等待時間(使用負值表示沒有限制) 默認 -1
spring.redis.lettuce.pool.max-wait=-1
# 連接池中的最大空閑連接 默認 8
spring.redis.lettuce.pool.max-idle=8
# 連接池中的最小空閑連接 默認 0
spring.redis.lettuce.pool.min-idle=0
四、添加 cache 的配置類
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
//使用注解@EnableCaching來開啟緩存。
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
//重新改造RedisTemplate這個對象的序列化格式
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
五、先測試下Redis的存取值
@RestController
@RequestMapping("/redis")
public class RedisController {
//這個是針對字符串操作的對象,可以直接使用,編碼格式沒問題
@Autowired
private StringRedisTemplate stringRedisTemplate;
//這個針對Object對象操作,不可直接使用,需要配置轉換規則才能使用
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@RequestMapping("/set")
public Object set(String key,String value) {
//往redis存放一個key和value的字符串、10秒后過期
stringRedisTemplate.opsForValue().set(key, value, 10,TimeUnit.SECONDS);
return "ok";
}
@RequestMapping("/get")
public Object get(String key) {
//redis中取一個key的值
return stringRedisTemplate.opsForValue().get(key);
}
@RequestMapping("/set2")
public Object set2(String key,String value) {
//如果沒給redisTemplate配置序列化規則,key前面總是會出現\xac\xed\x00\x05t\x00\b,產生這問題的原因是?
//redisTemplate 默認的序列化方式為 jdkSerializeable, StringRedisTemplate的默認序列化方式為StringRedisSerializer。
redisTemplate.opsForValue().set(key, new Student(1001, "張三", "123456", "1", 1));
return "ok";
}
@RequestMapping("/get2")
public Object get2(String key) {
//redis中取一個key的值
return redisTemplate.opsForValue().get(key);
}
}
六、緩存注解介紹
| 注解名 | 注解作用 |
|---|---|
| @EnableCaching | 開啟緩存功能 |
| @Cacheable | 定義緩存,用于觸發緩存 |
| @CachePut | 定義更新緩存,觸發緩存更新、會把使用的方法作為值緩存 |
| @CacheEvict | 定義清除緩存,觸發緩存清除 |
| @CacheConfig | 定義公共設置,位于class之上 |
七、service緩存注解使用
@Service
public class StudentService {
@Autowired
StudentDao dao;
//只要查詢一次,ji
//value+“::”+key 才是redis的key
//key一定要用單引號括起來
//實際上這個緩存的 key是由下面的 value::key 組成 aaa::bbb
//key也可以拼接參數進去
@Cacheable(value = "StudentService",key = "'getAll1'+#name")
public List<Student> getAll1(String name){
System.out.println("我是StudentService的getAll1"+name);
return dao.getAll1();
}
//根據參數對象緩存
@Cacheable(value = "StudentService",key = "'getAll1'+#info.name")
public List<Student> getAll3(Student info){
System.out.println("我是StudentService的getAll1"+info);
return dao.getAll1();
}
//更新緩存,會把返回的值重新緩存到這個key
@CachePut(value = "student",key = "'getAll2'")
public List<Student> getAll2(){
System.out.println("service層的getAll2方法");
return dao.getAll1();
}
//清除student::getAll1這個緩存key
@CacheEvict(value = "student",key = "'getAll1'")
public int deleteById(int id) {
System.out.println("service層的deleteById方法");
return dao.deleteById(id);
}
//清除student::getAll2這個緩存key
@CacheEvict(value = "student",key = "'getAll2'")
public int update(Student info) {
System.out.println("service層的update方法");
return dao.update(info);
}
//清除student下面的所有緩存:@CacheEvict(value = "student",allEntries = true)
@CacheEvict(value = "student",allEntries = true)
public void clear() {
System.out.println("清除所有緩存!!!");
}
}
八、controller使用緩存
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
StudentService service;
@RequestMapping("/getAll1")
public List<Student> getAll1(){
System.out.println("controller層的getAll1方法");
return service.getAll1();
}
@RequestMapping("/getAll2")
public List<Student> getAll2(){
System.out.println("controller層的getAll2方法");
return service.getAll2();
}
@RequestMapping("/deleteById")
public int deleteById(int id) {
System.out.println("controller層的deleteById方法");
return service.deleteById(id);
}
@RequestMapping("/update")
public int update(Student info) {
System.out.println("controller層的update方法");
return service.update(info);
}
@RequestMapping("/clear")
public void clear() {
System.out.println("controller清除所有緩存!!!");
service.clear();
}
}
浙公網安備 33010602011771號