-
步骤一:
导入整合坐标
<!--springboot 整合redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!--引入data-redis的依赖包:jackson--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> </dependency>
-
步骤二: RedisTemplate 模板类
手动装配这个类:RedisConfig
@Configuration @EnableCaching public class RedisConfig { //1.注入工厂对象 @Resource private RedisConnectionFactory redisConnectionFactory; //2.注入模板类对象 @Bean public RedisTemplate get(){ RedisTemplate redisTemplate = new RedisTemplate(); redisTemplate.setKeySerializer(new StringRedisSerializer());//将传入的key : 序列化 redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());//将传入的value : 序列化 redisTemplate.setConnectionFactory(redisConnectionFactory);//通过工厂获取连接对象,模板类建立了与redis连接 return redisTemplate; } }
-
步骤三:使用RedisTemplate 模板类操作redis数据库
@RunWith(SpringRunner.class) @SpringBootTest(classes = RedisApplication.class) public class Demo { @Autowired @Qualifier("redisTemplate") RedisTemplate redisTemplate; @Test public void testX1(){ //获取操作redis五种数据类型的对象 ValueOperations string_oper = redisTemplate.opsForValue(); ListOperations list_per = redisTemplate.opsForList(); HashOperations hash_per= redisTemplate.opsForHash(); SetOperations set_per= redisTemplate.opsForSet(); ZSetOperations zSet_oper= redisTemplate.opsForZSet(); } @Test public void testX(){ //获取操作redis五种数据类型的对象 ValueOperations string_oper = redisTemplate.opsForValue(); string_oper.set("ssss","AAA"); } }
-
步骤四: 启用redis缓存,在配置类RedisConfig加上注解: @EnableCaching //开启缓存
-
@Cacheable: 使用redis保存数据
-
@CachePut: 在做更新(添加/修改)方法后,更新redis缓存数据
-
@CacheEvict 应用到删除数据的方法上,调用方法时会从缓存中删除对应 key 的数据
相同的属性:属性里面可以使用spel表达式
value = "user",:redis缓存的名称
key = "ss", 缓存的key
unless = "条件表达式“: 当不满足条件时,使用redis保存数据,反之不保存
condition="条件表达式": 当满足条件时,使用redis保存数据,反之保存
@Service public class CategoryServiceImpl implements CategoryService { @Cacheable(value = "list33",key="#root.methodName",unless = "3>10") public List<String> findAll() { List<String> list = new ArrayList<String>(); list.add("phone"); list.add("computer"); list.add("clothes"); return list; } }
-