Spring Data Redis示例

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介:

说明

关于Redis:一个基于键值对存储的NoSQL内存数据库,可存储复杂的数据结构,如ListSetHashes

关于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]}



本文转自风一样的码农博客园博客,原文链接:http://www.cnblogs.com/chenpi/p/6329636.html,如需转载请自行联系原作者

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
1月前
|
NoSQL 安全 Java
Spring Boot3整合Redis
Spring Boot3整合Redis
62 1
|
1月前
|
存储 缓存 Java
【Spring原理高级进阶】有Redis为啥不用?深入剖析 Spring Cache:缓存的工作原理、缓存注解的使用方法与最佳实践
【Spring原理高级进阶】有Redis为啥不用?深入剖析 Spring Cache:缓存的工作原理、缓存注解的使用方法与最佳实践
|
1月前
|
缓存 NoSQL Java
spring cache整合redis实现springboot项目中的缓存功能
spring cache整合redis实现springboot项目中的缓存功能
46 1
|
1月前
|
存储 NoSQL Java
[Redis]——Spring整合Redis(SpringDataRedis)
[Redis]——Spring整合Redis(SpringDataRedis)
|
1月前
|
存储 Java 关系型数据库
Spring Batch学习记录及示例项目代码
Spring Batch学习记录及示例项目代码
|
1月前
|
Java 数据库 Spring
如何使用Spring Data JPA完成审计功能
如何使用Spring Data JPA完成审计功能
|
1月前
|
监控 NoSQL Java
Spring Boot集成Redis启动失败【Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool2.impl.G】
Spring Boot集成Redis启动失败【Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool2.impl.G】
|
1月前
|
NoSQL Java 定位技术
|
6月前
|
缓存 Java Go
解决Spring Data JPA查询存在缓存问题及解决方案
解决Spring Data JPA查询存在缓存问题及解决方案
358 0
|
4月前
|
XML Java 数据库连接
Spring Boot的数据访问之Spring Data JPA以及Hibernate的实战(超详细 附源码)
Spring Boot的数据访问之Spring Data JPA以及Hibernate的实战(超详细 附源码)
49 0

热门文章

最新文章