Spring Boot Redis Cache
在此章雁刷,我們將SpringBoot2.x集成Redis Cache剑刑,Redis是一個開源的,基于內(nèi)存的數(shù)據(jù)結(jié)構(gòu)存儲,可以用作數(shù)據(jù)庫凌节、緩存和消息代理钦听,在本章僅講解緩存集成。
準備工作
當前項目工具及環(huán)境
- 開發(fā)工具 IDEA 2018.3
- 依賴管理 Gradle 5.0
- JDK 1.8
- Redis
現(xiàn)在去初始化一個Spring網(wǎng)站初始生成一個SpringBoot項目
Spring Boot Redis 項目生成
進入網(wǎng)站 https://start.spring.io/
我們現(xiàn)在使用SPRING INITIALIZR
工具生成一個初始化項目倍奢,在這里我們初始了4個依賴包
點擊生成下載過來一個zip包朴上,解壓之后導(dǎo)入IDEA工具就可以了
項目導(dǎo)入開發(fā)環(huán)境
build.gradle文件和maven的pom.xml相似,可以構(gòu)建項目的依賴配置文件
在IDEA初始界面點擊OPEN -> 選擇文件 -> 找到.gradle文件 -> 選擇Open —> Open as Project
這里的gradle環(huán)境是本地的卒煞,很簡單安裝配置痪宰,gradle官網(wǎng)下載二進制包然后解壓,環(huán)境變量配置一下就可以使用了
Spring Boot Redis Cache Gradle Dependencies
上面我們已經(jīng)初始化了一個項目依賴文件build.gradle畔裕,我們也可以去手動修改然后添加或修改自己需要的依賴等
點擊上圖左上角停止下載衣撬,換成下面的國內(nèi)源之后在加載gradle
build.gradle
buildscript {
ext {
springBootVersion = '2.1.1.RELEASE'
}
repositories {
maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
mavenCentral()
}
dependencies {
implementation('org.springframework.boot:spring-boot-starter-data-jpa')
implementation('org.springframework.boot:spring-boot-starter-data-redis')
implementation('org.springframework.boot:spring-boot-starter-web')
runtimeOnly('com.h2database:h2')
testImplementation('org.springframework.boot:spring-boot-starter-test')
}
定義一個實體對象
要將數(shù)據(jù)存到redis,我們需要定義一個實體來進行交互扮饶,并需要序列化實體對象
User.java
package com.example.rediscache.model;
import javax.persistence.*;
import java.io.Serializable;
@Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "SEQ_GEN", sequenceName = "SEQ_USER", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_GEN")
private Long id;
private String name;
private long money;
public User() {
}
public User(String name, long money) {
this.name = name;
this.money = money;
}
//省略Getter 和 Setter
@Override
public String toString() {
return String.format("User{id=%d, name='%s', money=%d}", id, name, money);
}
}
配置 Redis Cache
使用springboot的依賴我們已經(jīng)用gradle來完成具练,除此之外我們還要配置下:
application.yml
# Redis Config
spring:
cache:
type: redis
redis:
host: localhost
port: 6379
password: pass1234
基于JPA的簡潔數(shù)據(jù)操作
UserRepository.java
package com.example.rediscache.repository;
import com.example.rediscache.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> { }
開啟緩存并初始化數(shù)據(jù)
在啟動類增加注解@EnableCaching
開啟緩存
并實現(xiàn)CommandLineRunner接口來執(zhí)行啟動完成之后的任務(wù)
RedisCacheApplication.java
package com.example.rediscache;
import com.example.rediscache.model.User;
import com.example.rediscache.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
//springboot啟動時執(zhí)行任務(wù)CommandLineRunner
@SpringBootApplication
//開啟緩存
@EnableCaching
public class RedisCacheApplication implements CommandLineRunner {
private final UserRepository userRepository;
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
public RedisCacheApplication(UserRepository userRepository) {
this.userRepository = userRepository;
}
public static void main(String[] args) {
SpringApplication.run(RedisCacheApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
logger.info("開始初始化user ->user count ->{}",userRepository.count());
User james = new User("James", 2000);
User potter = new User("Potter", 4000);
User dumbledore = new User("Dumbledore", 999999);
userRepository.save(james);
userRepository.save(potter);
userRepository.save(dumbledore);
logger.info("初始化完成 數(shù)據(jù)-> {}.", userRepository.findAll());
}
}
控制層骨架
UserController.java
package com.example.rediscache.controller;
import com.example.rediscache.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
@RestController
public class UserController {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final UserRepository userRepository;
@Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
//...dosomething
}
現(xiàn)在測試緩存
當我們數(shù)據(jù)庫查詢出來的值要放到緩存里,用@Cacheable
注解
@Cacheable(value = "users", key = "#userId", unless = "#result.money < 10000")
@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
public Object getUser(@PathVariable Long userId) {
logger.info("獲取user信息根據(jù)ID-> {}.", userId);
return userRepository.findById(userId);
}
我們訪問 localhost:8080/1 和 localhost:8080/3 分別兩次
發(fā)現(xiàn)id為3的就走了一次方法 說明緩存成功
id為1的走了兩次是因為 unless里條件成立就不會緩存到redis
更新緩存
每次當我們的數(shù)據(jù)庫的值要更改甜无,我們緩存的也要更改 扛点,我們可以使用 @CachePut 注解
@CachePut(value = "users", key = "#user.id")
@PutMapping("/update")
public User updatePersonByID(@RequestBody User user) {
userRepository.save(user);
return user;
}
刪除緩存
當我們的數(shù)據(jù)從數(shù)據(jù)庫刪除,我們也要從緩存進行刪除,我們可以使用 @CacheEvict
注解
allEntries 是否清空所有緩存內(nèi)容岂丘,缺省為 false占键,如果指定為 true,則方法調(diào)用后將立即清空所有緩存
@CacheEvict(value = "users", allEntries=true)
@DeleteMapping("/{id}")
public void deleteUserByID(@PathVariable Long id) {
logger.info("刪除用戶根據(jù)ID-> {}", id);
userRepository.deleteById(id);
}
在redis中查看已經(jīng)沒有了緩存
送上redis可視化工具
redis desktop manager for windows:
鏈接:https://pan.baidu.com/s/1tYwfM0sHLlDGDdQZc-26Sg 密碼:4ivg
redis desktop manager for mac:
鏈接:https://pan.baidu.com/s/1g9gxtLoAtm1IA0fA5Zs0qQ 密碼:aj0r