小鸡炸

导航

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();
	}
}

posted on 2022-01-19 10:31  小鸡炸  阅读(75)  评论(0编辑  收藏  举报