基于api和注解方式实现Redis缓存

一、api方式

Book类

implements Serializable和private static final long serialVersionUID = -1;实现序列化

@Data
@TableName("tb_book")
public class Book implements Serializable {
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    private String type;
    private String name;
    private String description;
    private static final long serialVersionUID = -1;
}

BookDao

mybatisplus

@Mapper
public interface BookDao extends BaseMapper<Book> {

}

BookService

public interface BookService extends IService<Book> {
    Book getBookById(Integer id);
    int updateBook(Book book);
    int deleteBook(Integer id);
}

BookServiceImpl

@Service
public class BookServiceImpl extends ServiceImpl<BookDao, Book> implements BookService {
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public Book getBookById(Integer id) {
        Book book = (Book) redisTemplate.opsForValue().get("book" + id);
        if (book != null)
            return book;
        else {
            book = this.baseMapper.selectById(id);
            redisTemplate.opsForValue().set("book" + id, book, 1, TimeUnit.DAYS);
            return book;
        }
    }

    @Override
    public int updateBook(Book book) {
        int res = this.baseMapper.updateById(book);
        redisTemplate.opsForValue().set("book" + book.getId(), book);
        return res;
    }

    @Override
    public int deleteBook(Integer id) {
        int res = this.baseMapper.deleteById(id);
        redisTemplate.delete("book" + id);
        return res;
    }
}
}

测试

@SpringBootTest
@EnableCaching
class Springboot0114ApplicationTests {
@Autowired
private BookService bookService;
    @Test
    void contextLoads() {
        Book boo1 = bookService.getBookById(4);
        System.out.println(boo1);
    }
}

在这里插入图片描述

二、注解方式

注解方式记得在主启动类上加@EnableCaching注解

StudentServiceImpl

@Service
public class StudentServiceImpl extends ServiceImpl<StudentDao, Student> implements StudentService {

    @Override
    @Cacheable(cacheNames = "student",unless="#result==null")
    public Student getStudentById(Integer id) {
        Student student = this.baseMapper.selectById(id);
        return student;
    }

    @Override
    @CachePut(cacheNames = "student",key="#student.id")
    public Student updateStudent(Student student) {
        int res = this.baseMapper.updateById(student);
        return student;
    }

    @Override
    @CacheEvict(cacheNames = "student")
    public int deleteStudent(Integer id) {
        int res = this.baseMapper.deleteById(id);
        return res;
    }
}

测试

@SpringBootTest
@EnableCaching
class Springboot0114ApplicationTests {
@Resource
private StudentService studentService;
  
@Test
    void testStudent(){
    Student student1 = studentService.getStudentById(2);
    System.out.println(student1);
}
}

在这里插入图片描述

RedisConfig

自定义序列化Json格式

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        // 使用JSON格式序列化对象,对缓存数据key和value进行转换
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
        // 解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 设置RedisTemplate模板API的序列化方式为JSON
        template.setDefaultSerializer(jacksonSeial);
        return template;
    }
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        // 分别创建String和JSON格式序列化对象,对缓存数据key和value进行转换
        RedisSerializer<String> strSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jacksonSeial =
                new Jackson2JsonRedisSerializer(Object.class);
        // 解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 定制缓存数据序列化方式及时效
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofDays(1))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(strSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jacksonSeial))
                .disableCachingNullValues();

        RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(config).build();
        return cacheManager;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程初学者01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值