SpringBoot2.x【七】整合 Redis 入門

SpringBoot2.x【七】整合 Redis 入門

首先,Redis是什麼?java

Redis是一個開源的,基於內存的鍵值數據存儲,用做數據庫,緩存和消息代理。在實現方面,Key-Value存儲表明NoSQL空間中最大和最老的成員之一。Redis支持數據結構,如字符串,散列,列表,集和帶範圍查詢的有序集。
在spring data redis的框架,能夠很容易地編寫,經過提供一個抽象的數據存儲使用Redis的鍵值存儲的Spring應用程序。 非關係型數據庫,基於內存,存取數據的速度不是關係型數據庫所能比擬的 redis是鍵值對(key-value)的數據庫mysql

有5中主要數據類型:web

  • 字符串類型 string
  • 散列類型 hash
  • 列表類型 list
  • 集合類型 set
  • 有序集合類型 zset

redis緩存爲啥速度快redis

這麼說吧,別人問你什麼是「redis」,若是你知道,你能夠直接吧啦吧啦一大堆,其實這個時候你的大腦就相似redis緩存,別人問的「redis」就是key,你說出來的結果就是value,而你若是不知道,你就去上網查,而後再告訴別人,這就相似於查詢數據庫了,你查了再告訴別人固然慢了!
你把腦殼裏的東西寫進筆記就相似redis持久化保存了;
你過了兩個月把這玩意忘了,就是redis的按期刪除了;
引自:blog.csdn.net/angleflyyy/…spring

準備工做

項目工具環境:sql

  • IDEA 2018.2
  • Gradle 4+
  • JDK1.8以上
  • redis服務器

設置Redis服務器

redis下載地址:redis.io/download
若是你的電腦是Mac:數據庫

brew install redis
複製代碼

而後運行redis服務器apache

cuifuandeMacBook-Pro:~ cuifuan$ redis-server
25336:C 29 Nov 2018 14:53:42.490 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
25336:C 29 Nov 2018 14:53:42.490 # Redis version=5.0.2, bits=64, commit=00000000, modified=0, pid=25336, just started
25336:C 29 Nov 2018 14:53:42.490 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
25336:M 29 Nov 2018 14:53:42.491 * Increased maximum number of open files to 10032 (it was originally set to 256).
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 5.0.2 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    ' , .-` | `, ) Running in standalone mode |`-._`-...-` __...-.``-._|'` _.-'| Port: 6379 | `-._ `._ / _.-'    |     PID: 25336
  `-._    `-._  `-./  _.-' _.-'                                   
 |`-._`-._    `-.__.-' _.-'_.-'| | `-._`-._ _.-'_.-' | http://redis.io `-._ `-._`-.__.-'_.-' _.-'                                   
 |`-._`-._    `-.__.-' _.-'_.-'| | `-._`-._ _.-'_.-' | `-._ `-._`-.__.-'_.-' _.-'                                   
      `-._    `-.__.-' _.-'                                       
          `-._        _.-' `-.__.-'                                               

25336:M 29 Nov 2018 14:53:42.492 # Server initialized
25336:M 29 Nov 2018 14:53:42.492 * Ready to accept connections
複製代碼

初始化項目

如今去Spring開始界面初始化一個項目json

這裏選擇的是Gradle,選擇完成點擊Generate Projrct生成項目,這個時候會自動下載一個壓縮包給你,解壓事後導入,導入IDEA教程:note.youdao.com/noteshare?i…緩存

Gradle 依賴管理

讓咱們在build.gradle中爲咱們正在構建的示例應用程序聲明必要的依賴項

buildscript {
    repositories {
        maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.1.0.RELEASE")
    }
}

apply plugin: 'java-library'
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/' }
}

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'
    implementation 'mysql:mysql-connector-java'
    implementation 'org.projectlombok:lombok'
    implementation 'org.apache.commons:commons-pool2:2.4.2'
    implementation 'com.alibaba:fastjson:1.2.51'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
複製代碼

開始使用

憑藉着SpringBoot的開箱即用的特色,集成Redis也不例外

  • redisTemplate.opsForValue();//操做字符串
  • redisTemplate.opsForHash();//操做hash
  • redisTemplate.opsForList();//操做list
  • redisTemplate.opsForSet();//操做set
  • redisTemplate.opsForZSet();//操做有序set

在Spring的測試類中開始使用:

redisTemplate.opsForValue().set("username","test");
複製代碼

執行事後發現存在redis中的數據:

亂碼

是亂的,是由於在set後redis會序列化key和value,因此咱們要在config中重寫一下redisTemplate
src/main/java/com/example/springbootredisdemo/config/RedisConfig.java

package com.example.springbootredisdemo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    private final RedisTemplate redisTemplate;

    @Autowired
    public RedisConfig(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Bean
    @SuppressWarnings("unchecked")
    public RedisTemplate<String, Object> redisTemplate() {
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        RedisSerializer<Object> jsonString = new GenericToStringSerializer<>(Object.class);
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(jsonString);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(jsonString);
        return redisTemplate;
    }

}
複製代碼

再去執行一下剛剛的方法

格式化

通過自定義的序列化以後能夠了,沒有亂碼了

opsForList()添加操做
@Test
    public void CsetListRedis(){
        List<String> trap = new ArrayList<>();
        trap.add("張三");
        trap.add("張無忌");
        trap.add("新垣結衣");
        //循環向userlist左添加值
        trap.forEach(value->redisTemplate.opsForList().leftPush("userlist",value));
        //向userlist右添加值
        redisTemplate.opsForList().rightPush("userlist","rightValue");
        log.info("userlist->{}",redisTemplate.opsForList().range("userlist",0,10));
    }
複製代碼

opsForList()刪除操做
@Test
    public void DlistRedisRemove(){
        redisTemplate.opsForList().remove("userlist",0,"張無忌");
    }
複製代碼

經過源碼看這裏有三個參數:

  • key 對應的是redis中存的key值
  • count 正數就是從左邊開始刪除 負數是從右面 例如-1就從右刪除第一個值爲value的,0表明刪除所有值爲value的
  • value 就是須要從list移除的值
opsForSet()添加操做

利用了set值的不可重複

@Test
    public void CsetRedis(){
        List<String> trap = new ArrayList<>();
        trap.add("張三");
        trap.add("里斯");
        trap.add("里斯");
        trap.add("張無忌");
        trap.add("新垣結衣");
        System.out.print(trap.toString());
        //循環向userlist左添加值
        trap.forEach(value->redisTemplate.opsForSet().add("userSet",value));
        log.info("取出userSet->{}",redisTemplate.opsForSet().members("userSet"));
    }
複製代碼

結果

符合了Set集合的無序和不可重複性

opsForSet()的刪除操做

這個刪除操做就比較容易了,直接根據set的key值,後面參數寫其須要刪除的value就能夠

@Test
    public void EsetRedisRemove(){
        redisTemplate.opsForSet().remove("userSet","張無忌");
    }
複製代碼
opsForHash()操做
//opsForHash()操做
    @Test
    public void FhashRedisAdd(){
        //添加
        redisTemplate.opsForHash().put("user","phone",10086);
        redisTemplate.opsForHash().put("user","address","Shanghai");
        redisTemplate.opsForHash().put("user","del","mubaba");
        redisTemplate.opsForHash().put("user","dada","達達");
        //修改
        redisTemplate.opsForHash().put("user","address","Beijing");
        //刪除
        redisTemplate.opsForHash().delete("user","del","dada");
    }
複製代碼

結果

測試類SpringbootRedisDemoApplicationTests

src/test/java/com/example/springbootredisdemo/SpringbootRedisDemoApplicationTests.java

package com.example.springbootredisdemo;

import com.example.springbootredisdemo.service.NovelService;
import lombok.extern.slf4j.Slf4j;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;

//根據測試方法名字搞定執行順序
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class SpringbootRedisDemoApplicationTests {

    @Autowired
    private NovelService novelService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    private final static String KEY = "username";
    private final static String VALUE = "test";


    @Test
    public void AstringRedis(){
        redisTemplate.opsForValue().set(KEY,VALUE);
        log.info("string set存儲:{}->{}",KEY,VALUE);
        redisTemplate.opsForValue().get(KEY);
        log.info("string 根據{}取出{}",KEY,VALUE);
    }

    @Test
    public void BlistRedis(){
        List<String> trap = new ArrayList<>();
        trap.add("張三");
        trap.add("張三");
        trap.add("張無忌");
        trap.add("新垣結衣");
        //循環向userlist左添加值
        trap.forEach(value->redisTemplate.opsForList().leftPush("userlist",value));
// redisTemplate.opsForList().leftPushAll("userlist",trap);
        //向userlist右添加值
        redisTemplate.opsForList().rightPush("userlist","rightValue");
        //取出userlist的值
        log.info("userlist->{}",redisTemplate.opsForList().range("userlist",0,10));
    }

    @Test
    public void CsetRedis(){
        List<String> trap = new ArrayList<>();
        trap.add("張三");
        trap.add("里斯");
        trap.add("里斯");
        trap.add("張無忌");
        trap.add("新垣結衣");
        System.out.print(trap.toString());
        //循環向userlist左添加值
        trap.forEach(value->redisTemplate.opsForSet().add("userSet",value));
        log.info("取出userSet->{}",redisTemplate.opsForSet().members("userSet"));
    }

    @Test
    public void DlistRedisRemove(){
        redisTemplate.opsForList().remove("userlist",0,"張無忌");
    }


    @Test
    public void EsetRedisRemove(){
        redisTemplate.opsForSet().remove("userSet","張無忌");
    }

    //opsForHash()操做
    @Test
    public void FhashRedisAdd(){
        //添加
        redisTemplate.opsForHash().put("user","phone",10086);
        redisTemplate.opsForHash().put("user","address","Shanghai");
        redisTemplate.opsForHash().put("user","del","mubaba");
        redisTemplate.opsForHash().put("user","dada","達達");
        //修改
        redisTemplate.opsForHash().put("user","address","Beijing");
        //刪除
        redisTemplate.opsForHash().delete("user","del","dada");
    }
}
複製代碼
小知識

方法名字前加ABCD...是爲了讓方法有執行順序,根據測試方法名字搞定執行順序,在方法上加註解 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
日誌註解@Slf4j是爲了讓日誌書寫更方便

//以前寫日誌  
 log.info("輸出a"+index+"b");
 //如今
 log.info("輸出a{}b",index);
複製代碼

多個參數能夠用多個{},總之,喜歡哪一個用哪一個,謝謝!

相關文章
相關標籤/搜索