Spring Data Redis樣本,springredis

來源:互聯網
上載者:User

Spring Data Redis樣本,springredis
說明

關於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資料庫。

@Configurationpublic 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;@Repositorypublic 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的使用者後,查看剩餘的使用者

@SpringBootApplicationpublic 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/

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.