Spring Data Redis示例

来源:http://www.cnblogs.com/chenpi/archive/2017/01/21/6329636.html
-Advertisement-
Play Games

說明 關於Redis:一個基於鍵值對存儲的NoSQL記憶體資料庫,可存儲複雜的數據結構,如List, Set, Hashes。 關於Spring Data Redis:簡稱SDR, 能讓Spring應用更加方便配置和訪問Redis。 本工程基於spring boot ,spring data redi ...


說明

關於Redis:一個基於鍵值對存儲的NoSQL記憶體資料庫,可存儲複雜的數據結構,如List, Set, Hashes

關於Spring Data Redis:簡稱SDR, 能讓Spring應用更加方便配置和訪問Redis。

本工程基於spring boot ,spring data redis,  spring io platform實現。

POM配置

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.edu.hdu</groupId>
    <artifactId>examples.sdr</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>examples.sdr</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>io.spring.platform</groupId>
                <artifactId>platform-bom</artifactId>
                <version>Athens-SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <dependency>
                <!-- Import dependency management from Spring Boot -->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>1.4.3.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!-- Compile -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- Test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>examples.sdr</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.4.3.RELEASE</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            
        </plugins>
    </build>

</project>

配置RedisTemplate Bean

主要生成兩個bean,JedisConnectionFactory 和 RedisTemplate,RedisTemplate bean用於後續註入到PersonRepoImpl中操作Redis資料庫。

@Configuration
public class RedisConfig
{
    @Bean
    JedisConnectionFactory jedisConnectionFactory()
    {
        JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
        connectionFactory.setHostName("127.0.0.1");
        connectionFactory.setPort(6379);
        return new JedisConnectionFactory();
    }

    @Bean
    @Autowired
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory)
    {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        return template;
    }
        
}

使用RedisTemplate操作Redis

這裡我們通過RedisTemplate得到HashOperations對象,使用該對象來存取Redis數據。

package cn.edu.hdu.examples.sdr.repo.impl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import cn.edu.hdu.examples.sdr.bean.Person;
import cn.edu.hdu.examples.sdr.repo.PersonRepo;

@Repository
public class PersonRepoImpl implements PersonRepo {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static String PERSON_KEY = "Person";

    @Override
    public void save(Person person) {
        this.redisTemplate.opsForHash().put(PERSON_KEY, person.getId(), person);
    }

    @Override
    public Person find(String id) {
        return (Person) this.redisTemplate.opsForHash().get(PERSON_KEY, id);
    }

    @Override
    public Map<Object, Object> findAll() {
        return this.redisTemplate.opsForHash().entries(PERSON_KEY);
    }

    @Override
    public void delete(String id) {
        this.redisTemplate.opsForHash().delete(PERSON_KEY, id);

    }

}

測試

使用如下代碼進行測試,運行前,請先運行本地redis服務;

1、查看當前所有用戶

2、存入三個用戶

3、查看ID為3的用戶

4、查看所有用戶

5、刪除ID為2的用戶後,查看剩餘的用戶

@SpringBootApplication
public class Application implements CommandLineRunner {
    @Autowired
    private PersonRepo personRepo;

    
    public void testHash(){
           Map<Object, Object> personMatrixMap = personRepo.findAll();
            System.out.println("@@當前Redis存儲的所有用戶:" + personMatrixMap);
            
            Person person = new Person();
            person.setId("1");
            person.setAge(55);
            person.setGender(Gender.Female);
            person.setName("Oracle");

            personRepo.save(person);

            Person person2 = new Person();
            person2.setId("2");
            person2.setAge(60);
            person2.setGender(Gender.Male);
            person2.setName("TheArchitect");

            personRepo.save(person2);

            Person person3 = new Person();
            person3.setId("3");
            person3.setAge(25);
            person3.setGender(Gender.Male);
            person3.setName("TheOne");

            personRepo.save(person3);

            System.out.println("查找ID為3的用戶 : " + personRepo.find("3"));

            personMatrixMap = personRepo.findAll();

            System.out.println("當前Redis存儲的所有用戶:" + personMatrixMap);

            personRepo.delete("2");

            personMatrixMap = personRepo.findAll();

            System.out.println("刪除ID為2的用戶後,剩餘的所有用戶: " + personMatrixMap);
    }
    
    
    
    @Override
    public void run(String... args) throws Exception {
        this.testHash();

    }

    public static void main(String[] args) {
        // Close the context so it doesn't stay awake listening for redis
        SpringApplication.run(Application.class, args).close();

    }
}

結果列印:

@@當前Redis存儲的所有用戶:{}
查找ID為3的用戶 : Person [id=3, name=TheOne, gender=Male, age=25]
當前Redis存儲的所有用戶:{2=Person [id=2, name=TheArchitect, gender=Male, age=60], 3=Person [id=3, name=TheOne, gender=Male, age=25], 1=Person [id=1, name=Oracle, gender=Female, age=55]}
刪除ID為2的用戶後,剩餘的所有用戶: {3=Person [id=3, name=TheOne, gender=Male, age=25], 1=Person [id=1, name=Oracle, gender=Female, age=55]}

也可以打開redis-cli手動輸入key, 查看當前Redis存儲結果:

剩下的兩個用戶為:{3=Person [id=3, name=TheOne, gender=Male, age=25], 1=Person [id=1, name=Oracle, gender=Female, age=55]}

例子源碼

https://github.com/peterchenhdu/spring-data-redis-example

參考資料

https://examples.javacodegeeks.com/enterprise-java/spring/spring-data-redis-example/

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • JDK、JRE、JVM JDK包含JRE,而JRE包含JVM JDK(Java Development Kit)是針對Java開發員的產品,是整個Java的核心,包括了Java運行環境JRE、Java工具和Java基礎類庫。Java Runtime Environment(JRE)是運行JAVA程式 ...
  • 我安裝的是Myeclipse 10.7.1。裝上好久沒用,今天啟動突然報錯:Failed to create the Java Virtual Machine。 檢查Myeclipse安裝好使用時好的啊,近期也沒用,可能是近期升級了本地單獨安裝的jre版本導致的吧(Myeclipse使用自己的jre... ...
  • 歡迎任何形式的轉載,但請務必註明出處。 1.jdk安裝及環境配置 點擊進入教程 2.Eclipse安裝 點擊進入官網下載 註意下載完成打開.exe後,出現的界面,有很多版本供選擇。選擇下圖版本 3.Tomcat安裝及環境配置 點擊進入教程 4.配置Tomcat伺服器 註意我下載的是V9.0版本,根據 ...
  • Java程式員編程時需要混合面向對象思維和一般命令式編程的方法,能否完美的將兩者結合起來完全得依靠編程人員的水準: 技能(任何人都能容易學會命令式編程) 模式(有些人用“模式-模式”,舉個例子,模式可以應用到任何地方,而且都可以歸為某一類模式) 心境(首先,要寫個好的面向對象程式是比命令式程式難的多 ...
  • Java語言基礎之常量: 概念: 在程式執行中,其值不可發生改變的量,稱為常量 常量在程式運行過程中主要有兩個作用: 1.代表常數,便於常數的修改; 2.增強程式的可讀性。 常量的分類: 字面值常量 自定義常量(面向對象部分講) 字面值常量的分類: 1. 整型常量:整型常量的值為整數的類型,它可以採 ...
  • 題目大意: 在n*n(n<=512)的網格上,從邊界某個點出發,經過每個點一次且回到邊界上,構造出一種方案使拐彎的數量至少為n*(n-1)-1次。 構造方法:我們可以手算出n=2~6時的方案。 n=2: n=3: n=4: n=5: n=6: 觀察n=2與n=4、n=3與n=5的情況我們可以得到一種 ...
  • <! TOC "algorithmn" "parameter" "code" "主要是以下三個函數" "計算所有的可行點" "怎麼計算一個點的可行點" "從可行點中計算路徑path" "todo" <! /TOC algorithmn "演算法的解釋" "Dijkstra" 其實就是A star或者D ...
  • 網路基礎 協議的概念 什麼是協議 從應用的角度出發,協議可理解為“規則”,是數據傳輸和數據的解釋的規則。 假設,A、B雙方欲傳輸文件。規定: 第一次,傳輸文件名,接收方接收到文件名,應答OK給傳輸方; 第二次,發送文件的尺寸,接收方接收到該數據再次應答一個OK; 第三次,傳輸文件內容。同樣,接收方接 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...