功用缓慢是开发人员经常面临的一个反复出现且杂乱的问题。解决此类问题的最常见办法之一是经过缓存。实际上,这种机制答应在任何类型的使用程序的功用方面完成显着改善。问题是处理缓存并不是一件简单的事。走运的是,Spring Boot 透明地供给了缓存,这要归功于 Spring Boot 缓存笼统,这是一种答应共同运用各种缓存办法而对代码影响最小的机制。让咱们看看开端处理它应该知道的一切。
首要,咱们将介绍缓存的概念。然后,咱们将研究最常见的 Spring Boot 缓存相关注解,了解最重要的注解是什么,在哪里以及如何运用它们。接下来,是时分看看在撰写本文时 Spring Boot 支撑的最流行的缓存引擎有哪些。最后,咱们将经过一个示例了解 Spring Boot 缓存的实际使用。
什么是缓存
缓存是一种旨在进步任何类型使用程序功用的机制。它依靠于缓存,缓存可以看作是一种暂时的快速访问软件或硬件组件,用于存储数据以削减处理与相同数据相关的未来恳求所需的时刻。处理缓存是很杂乱的,但把握这个概念关于任何开发人员来说简直都是不可避免的。假如您有兴趣深入研究缓存、了解它是什么、它是如何作业的以及它最重要的类型是什么,您应该首要点击这个链接。
如安在 Spring Boot 使用程序中完成 Redis 缓存?
为了运用 Spring Boot 完成 Redis 缓存,咱们需求创立一个小型使用程序,该使用程序将具有 CRUD 操作。然后咱们将在检索、更新和删去操作中使用 Redis 缓存功用。
咱们将运用 REST 创立一个 CRUD 使用程序。在这里,假定咱们的实体类是 Invoice.java。为了创立一个完整的 REST 使用程序,咱们将依据行业最佳实践拥有控制器、服务和存储库层。一旦咱们完成了 Invoice REST Application 的开发,咱们将进一步在某些办法上使用注解来获得 Redis Cache 的优点。这是在咱们的使用程序中完成 Redis 缓存的分步办法。
需求引入的依靠
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置文件
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/rediscachetest
spring.datasource.username=root
spring.datasource.password=****
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.cache.type=redis
spring.cache.redis.cache-null-values=true
#spring.cache.redis.time-to-live=40000
启动类注解 @EnableCaching at starter class
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class RedisAsaCacheWithSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(RedisAsaCacheWithSpringBootApplication.class, args);
}
}
创立 Invoice.java实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Invoice implements Serializable{
private static final long serialVersionUID = -4439114469417994311L;
@Id
@GeneratedValue
private Integer invId;
private String invName;
private Double invAmount;
}
创立一个接口 InvoiceRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.dev.springboot.redis.model.Invoice;
@Repository
public interface InvoiceRepository extends JpaRepository<Invoice, Integer> {
}
自定义异常类
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class InvoiceNotFoundException extends RuntimeException {
private static final long serialVersionUID = 7428051251365675318L;
public InvoiceNotFoundException(String message) {
super(message);
}
}
一个具体的完成类,中心包含一些增删改查的办法
import com.dev.springboot.redis.model.Invoice;
import java.util.List;
public interface InvoiceService {
public Invoice saveInvoice(Invoice inv);
public Invoice updateInvoice(Invoice inv, Integer invId);
public void deleteInvoice(Integer invId);
public Invoice getOneInvoice(Integer invId);
public List<Invoice> getAllInvoices();
}
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.dev.springboot.redis.exception.InvoiceNotFoundException;
import com.dev.springboot.redis.model.Invoice;
import com.dev.springboot.redis.repo.InvoiceRepository;
@Service
public class InvoiceServiceImpl implements InvoiceService {
@Autowired
private InvoiceRepository invoiceRepo;
@Override
public Invoice saveInvoice(Invoice inv) {
return invoiceRepo.save(inv);
}
@Override
@CachePut(value="Invoice", key="#invId")
public Invoice updateInvoice(Invoice inv, Integer invId) {
Invoice invoice = invoiceRepo.findById(invId)
.orElseThrow(() -> new InvoiceNotFoundException("Invoice Not Found"));
invoice.setInvAmount(inv.getInvAmount());
invoice.setInvName(inv.getInvName());
return invoiceRepo.save(invoice);
}
@Override
@CacheEvict(value="Invoice", key="#invId")
// @CacheEvict(value="Invoice", allEntries=true) //in case there are multiple records to delete
public void deleteInvoice(Integer invId) {
Invoice invoice = invoiceRepo.findById(invId)
.orElseThrow(() -> new InvoiceNotFoundException("Invoice Not Found"));
invoiceRepo.delete(invoice);
}
@Override
@Cacheable(value="Invoice", key="#invId")
public Invoice getOneInvoice(Integer invId) {
Invoice invoice = invoiceRepo.findById(invId)
.orElseThrow(() -> new InvoiceNotFoundException("Invoice Not Found"));
return invoice;
}
@Override
@Cacheable(value="Invoice")
public List<Invoice> getAllInvoices() {
return invoiceRepo.findAll();
}
}
添加Controller接口,进行恳求测验
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dev.springboot.redis.model.Invoice;
import com.dev.springboot.redis.service.InvoiceService;
@RestController
@RequestMapping("/invoice")
public class InvoiceController {
@Autowired
InvoiceService invoiceService;
@PostMapping("/saveInv")
public Invoice saveInvoice(@RequestBody Invoice inv) {
return invoiceService.saveInvoice(inv);
}
@GetMapping("/allInv")
public ResponseEntity<List<Invoice>> getAllInvoices(){
return ResponseEntity.ok(invoiceService.getAllInvoices());
}
@GetMapping("/getOne/{id}")
public Invoice getOneInvoice(@PathVariable Integer id) {
return invoiceService.getOneInvoice(id);
}
@PutMapping("/modify/{id}")
public Invoice updateInvoice(@RequestBody Invoice inv, @PathVariable Integer id) {
return invoiceService.updateInvoice(inv, id);
}
@DeleteMapping("/delete/{id}")
public String deleteInvoice(@PathVariable Integer id) {
invoiceService.deleteInvoice(id);
return "Employee with id: "+id+ " Deleted !";
}
}
我的博客即将同步至腾讯云开发者社区,邀请我们一起入驻:cloud.tencent.com/developer/s…