mybatis 启用 redis 缓存

550人浏览 / 0人评论

pom.xml

<!--redis-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
  </dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
  <exclusions>
    <exclusion>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
    </exclusion>
    <exclusion>
      <groupId>io.lettuce</groupId>
      <artifactId>lettuce-core</artifactId>
    </exclusion>
  </exclusions>
</dependency>
<dependency><!--可加可不加-->
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
</dependency>

application.yml

spring:
  application:
    name: springboot1
  cache:
    type: redis
  redis:
    host: 127.0.0.1
    port: 6379
    password: admin123

启动类

添加 @EnableCaching 注解。

RedisConfig.java

@Configuration
public class RedisConfig{
 
//以二进制型式存储
//@Bean
//@ConfigurationProperties(prefix="spring.redis")
//JedisConnectionFactory jedisConnectionFactory(){
//  return new JedisConnectionFactory();
//}
 
//以JSON型式存储
@Bean
public RedisCacheManager jsonCacheManager(RedisConnectionFactory factory){
  RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
  .serializeValuesWith(RedisSerializationContext.SerializationPair
  .fromSerializer(new GenericJackson2JsonRedisSerializer()));
  return RedisCacheManager.builder(factory)
  .cacheDefaults(config)
  .build();
}

测试

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=SpringBootTest.WebEnvironment.NONE)
class Springboot1ApplicationTests{
   
  @Autowired
  private StringRedisTemplate stringRedisTemplate;
   
  @Test
  void myRedisTest(){
    Jedis jedis = new Jedis("127.0.0.1",6379);
    System.out.println(jedis.isConnected());
    jedis.auth("admin123");
    System.err.println(jedis.ping());;
  }
   
  @Test
  void contextLoads(){
    stringRedisTemplate.opsForValue().set("k1","v1");
    System.err.println(stringRedisTemplate.opsForValue().get("k1"));
    System.err.println(stringRedisTemplate.opsForValue().get("Reservoir::1347466110682181634"));
  }
 
}

controller 中使用

@RestController
public class RedisController{
 
  @Autowired
  private IIomsReservoirService reservoirService;
   
  @PostMapping("IomsReservoir")
  public String reservoirAdd(IomsReservoir reservoir){
    return reservoirService.save(reservoir)?"success":"fail";
  }
   
  /**
  *@desc 添加缓存
  *缓存名字为"Reservoir","reservoirId"作为key
  *@method
  */
  @Cacheable(cacheNames="Reservoir",key="#reservoirId")
  @GetMapping("/testCacheAble/{reservoirId}")
  public IomsReservoir testCacheAble(@PathVariable("reservoirId")String reservoirId){
    return reservoirService.getById(reservoirId);
  }
   
  /**
  *@desc 更新缓存
  *缓存名字为"Reservoir","reservoirId"作为key
  *@method
  */
  @CachePut(cacheNames="Reservoir",key="#reservoirId")
  @GetMapping("/testCachePut/{reservoirId}")
  public IomsReservoir testCachePut(@PathVariable("reservoirId")String reservoirId){
    return reservoirService.getById(reservoirId);
  }
   
  /**
  *@desc 根据key删除缓存
  *测试CacheEvict注解清空指定用户缓存
  *@method
  */
  @CacheEvict(cacheNames="Reservoir",key="#reservoirId")
  @GetMapping("/testCacheEvict/{reservoirId}")
  public String testCacheEvict(@PathVariable("reservoirId")String reservoirId){
    return "cache for"+reservoirId+"has been flushed";
  }
   
  /**
  *@desc 清空所有cacheNames等于Reservoir的缓存
  * 测试CacheEvict注解的allEntries属性清空所有用户缓存
  *@method
  */
  @CacheEvict(cacheNames="Reservoir",allEntries=true)
  @GetMapping("/testAllEntries")
  public String testAllEntries(){
    return "All caches have been flushed";
  }
 
}

备注

1、cacheNames 也可以统一写在类上面, @CacheConfig(cacheNames = "product") ,具体的方法上就不用写啦。

@CacheConfig(cacheNames = "product")
public class BuyerOrderController {
    @PostMapping("/cancel")
    @CachePut(key = "456")
    public ResultVO cancel(@RequestParam("openid") String openid,
                           @RequestParam("orderId") String orderId){
        buyerService.cancelOrder(openid, orderId);
        return ResultVOUtils.success();
    }
}

2、Key 也可以动态设置为方法的参数:key="#参数",或者 key="#user.id"

@GetMapping("/detail")
@Cacheable(cacheNames = "prodcut", key = "#openid")
public ResultVO<OrderDTO> detail(@RequestParam("openid") String openid,@RequestParam("orderId") String orderId){
    OrderDTO orderDTO = buyerService.findOrderOne(openid, orderId);
    return ResultVOUtils.success(orderDTO);
}

3、缓存还可以设置条件
设置当 openid 的长度大于3时才缓存:

@GetMapping("/detail")
@Cacheable(cacheNames = "prodcut", key = "#openid", condition = "#openid.length > 3")
public ResultVO<OrderDTO> detail(@RequestParam("openid") String openid,@RequestParam("orderId") String orderId){
    OrderDTO orderDTO = buyerService.findOrderOne(openid, orderId);
    return ResultVOUtils.success(orderDTO);
}

还可以指定 unless 即条件不成立时缓存。#result 代表返回值,意思是当返回码不等于 0 时不缓存,也就是等于 0 时才缓存:

@GetMapping("/detail")
@Cacheable(cacheNames = "prodcut", key = "#openid", condition = "#openid.length > 3", unless = "#result.code != 0")
public ResultVO<OrderDTO> detail(@RequestParam("openid") String openid,@RequestParam("orderId") String orderId){
    OrderDTO orderDTO = buyerService.findOrderOne(openid, orderId);
    return ResultVOUtils.success(orderDTO);
}

全部评论