SpringBoot2.x【八】集成Redis緩存

SpringBoot2.x【八】集成Redis緩存

在此章,咱們將SpringBoot2.x集成Redis Cache,Redis是一個開源的,基於內存的數據結構存儲,能夠用做數據庫、緩存和消息代理,在本章僅講解緩存集成。java

準備工做

當前項目工具及環境git

  • 開發工具 IDEA 2018.3
  • 依賴管理 Gradle 5.0
  • JDK 1.8
  • Redis

如今去初始化一個Spring網站初始生成一個SpringBoot項目github

Spring Boot Redis 項目生成

進入網站 start.spring.io/
咱們如今使用SPRING INITIALIZR工具生成一個初始化項目,在這裏咱們初始了4個依賴包web

點擊生成下載過來一個zip包,解壓以後導入IDEA工具就能夠了redis

項目導入開發環境

build.gradle文件和maven的pom.xml類似,能夠構建項目的依賴配置文件spring

在IDEA初始界面點擊OPEN -> 選擇文件 -> 找到.gradle文件 -> 選擇Open —> Open as Project數據庫

這裏的gradle環境是本地的,很簡單安裝配置,gradle官網下載二進制包而後解壓,環境變量配置一下就可使用了windows

Spring Boot Redis Cache Gradle Dependencies

上面咱們已經初始化了一個項目依賴文件build.gradle,咱們也能夠去手動修改而後添加或修改本身須要的依賴等
緩存


點擊上圖左上角中止下載,換成下面的國內源以後在加載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')
}
複製代碼

定義一個實體對象

要將數據存到redis,咱們須要定義一個實體來進行交互,並須要序列化實體對象springboot

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的依賴咱們已經用gradle來完成,除此以外咱們還要配置下:
application.yml

# Redis Config
spring:
  cache:
    type: redis
  redis:
    host: localhost
    port: 6379
    password: pass1234

複製代碼
基於JPA的簡潔數據操做

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> { }

複製代碼
開啓緩存並初始化數據

在啓動類增長註解@EnableCaching開啓緩存
並實現CommandLineRunner接口來執行啓動完成以後的任務
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啓動時執行任務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("初始化完成 數據-> {}.", 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
}

複製代碼
如今測試緩存

當咱們數據庫查詢出來的值要放到緩存裏,用@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信息根據ID-> {}.", userId);
        return userRepository.findById(userId);
    }
複製代碼

咱們訪問 localhost:8080/1 和 localhost:8080/3 分別兩次

發現id爲3的就走了一次方法 說明緩存成功
id爲1的走了兩次是由於 unless裏條件成立就不會緩存到redis

更新緩存

每次當咱們的數據庫的值要更改,咱們緩存的也要更改 ,咱們可使用 @CachePut 註解

@CachePut(value = "users", key = "#user.id")
    @PutMapping("/update")
    public User updatePersonByID(@RequestBody User user) {
        userRepository.save(user);
        return user;
    }
複製代碼

刪除緩存

當咱們的數據從數據庫刪除,咱們也要從緩存進行刪除,咱們可使用 @CacheEvict 註解
allEntries 是否清空全部緩存內容,缺省爲 false,若是指定爲 true,則方法調用後將當即清空全部緩存

@CacheEvict(value = "users", allEntries=true)
    @DeleteMapping("/{id}")
    public void deleteUserByID(@PathVariable Long id) {
        logger.info("刪除用戶根據ID-> {}", id);
        userRepository.deleteById(id);
    }
複製代碼

在redis中查看已經沒有了緩存

送上redis可視化工具 redis desktop manager for windows:
下載連接 : github.com/cuifuan/spr… redis desktop manager for mac:
下載連接:github.com/cuifuan/spr…

相關文章
相關標籤/搜索