spring cache

相关注解

spring boot cache 提供了一些注解方便做cache应用。

(1)@CacheConfig:主要用于配置该类中会用到的一些共用的缓存配置

(2)@Cacheable:主要方法返回值加入缓存。同时在查询时,会先从缓存中取,若不存在才再发起对数据库的访问。

(3)@CachePut:配置于函数上,能够根据参数定义条件进行缓存,与@Cacheable不同的是,每次回真实调用函数,所以主要用于数据新增和修改操作上。

(4)@CacheEvict:配置于函数上,通常用在删除方法上,用来从缓存中移除对应数据

(5)@Caching:配置于函数上,组合多个Cache注解使用。

@Cacheable

@Cacheable 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存

/** * 根据ID获取Tasklog * @param id * @return */
@Cacheable(value = CACHE_KEY, key = "#id",condition = "#result != null")
public Tasklog findById(String id){
    System.out.println("FINDBYID");
    System.out.println("ID:"+id);
    return taskLogMapper.selectById(id);
}

@CachePut

@CachePut 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用

@CachePut(value=”my cache”)key缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合 @CachePut(value=”testcache”,key=”#userName”)condition 缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存

/** * 添加tasklog * @param tasklog * @return */
@CachePut(value = CACHE_KEY, key = "#tasklog.id")
public Tasklog create(Tasklog tasklog){
    System.out.println("CREATE");
    System.err.println (tasklog);
    taskLogMapper.insert(tasklog);
    return tasklog;
}

@CacheEvict

@CachEvict 的作用 主要针对方法配置,能够根据一定的条件对缓存进行清空

value 意思是:指定需要删除的缓存信息

allEntries 意思是:是否删除整个缓存(value中指定的值),默认是false

key属性是用来指定Spring缓存方法的返回结果时对应的key的

/** * 根据ID删除Tasklog * @param id */
@CacheEvict(value = CACHE_KEY, key = "#id")
public void delete(String id){
    System.out.println("DELETE");
    System.out.println("ID:"+id);
    taskLogMapper.deleteById(id);
}

@Caching

有时候我们可能组合多个Cache注解使用;

比如用户新增成功后,我们要添加id–>user;username—>user;email—>user的缓存;此时就需要@Caching组合多个注解标签了。

@Caching(put = {
    @CachePut(value = "user", key = "#user.id"),
    @CachePut(value = "user", key = "#user.username"),
    @CachePut(value = "user", key = "#user.email")
})
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface UserSaveCache {
}

案例代码

package com.example.cacheone.service;

import com.example.cacheone.dao.StudentDao;
import com.example.cacheone.entity.Student;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService  {

    @Resource
    private StudentDao studentDao;

    @Override
    @Cacheable("users")
    public List<Student> findAll() {
        return this.studentDao.findAll();
    }

    @Override
    @Cacheable(value = "user",key = "#id")
    public Student findById(int id) {
        return this.studentDao.findById(id).get();
    }

    @Override
    @CachePut(key = "p0.id")
    public Student save(Student student) {
        Student save = this.studentDao.save(student);
        return save;
    }

    @Override
    @CacheEvict(value = "users",key = "#id")
    public void deleteById(int id) {
         this.studentDao.deleteById(id);
    }
}

与Redis的整合

导入依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>

控制器

package com.example.cacheredis.controller;

import com.example.cacheredis.entity.Student;
import com.example.cacheredis.service.StudentService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
public class StudentController {

    @Resource
    private StudentService studentService;

    @GetMapping("/users")
    public List<Student> findAll(){
        return  this.studentService.findAll();
    }

    @DeleteMapping("/{id}")
    public boolean delelet(@PathVariable("id") int id){
        this.studentService.deleteById(id);
        this.studentService.flushAll();
        return true;
    }

    @GetMapping("/{id}")
    public Student findById(@PathVariable("id")int id){
        return this.studentService.findById(id);
    }

    @PutMapping("/{id}")
    public boolean update(Student student){
        this.studentService.save(student);
        this.studentService.flushAll();
        return true;
    }

    @PostMapping("")
    public boolean add(Student student){
        this.studentService.save(student);
        this.studentService.flushAll();
        return true;
    }
}

启动类

@SpringBootApplication
@EnableCaching
public class CacheRedisApplication {

业务

package com.example.cacheredis.service;

import com.example.cacheredis.dao.StudentDao;
import com.example.cacheredis.entity.Student;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService  {

    @Resource
    private StudentDao studentDao;

    @Override
    @Cacheable("students")
    public List<Student> findAll() { return this.studentDao.findAll();
    }

    @Override
    @Cacheable(value = "students",key = "#id")
    public Student findById(int id) {
        return this.studentDao.findById(id).get();
    }

    @Override
    @CachePut(value = "students",key = "#student.id")
    public Student save(Student student) {
        Student stu =this.studentDao.save(student);
        return stu;
    }

    @Override
    @CacheEvict(value = "students",key = "#id")
    public void deleteById(int id) {
         this.studentDao.deleteById(id);
    }


    @Override
    @CacheEvict(value ="students",allEntries = true)
    public void flushAll() {}
}

yaml

spring:
  jpa:
    properties:
      hibernate:
        format_sql: true
    hibernate:
      ddl-auto: update
    generate-ddl: true
    database: MYSQL
    show-sql: true

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值