说明

关于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/

Spring Data Redis示例的更多相关文章

  1. Spring Data Redis入门示例:数据序列化 (四)

    概述 RedisTemplate默认使用的是基于JDK的序列化器,所以存储在Redis的数据如果不经过相应的反序列化,看到的结果是这个样子的: 可以看到,出现了乱码,在程序层面上,不会影响程序的运行, ...

  2. Spring Data Redis入门示例:基于Jedis及底层API (二)

    使用底层API:RedisConnectionFactory和RedisConnection可以直接操作Redis,下面是一个简单的例子: ### Maven依赖 <properties> ...

  3. Spring Data Redis入门示例:字符串操作(六)

    Spring Data Redis对字符串的操作,封装在了ValueOperations和BoundValueOperations中,在集成好了SPD之后,在需要的地方引入: // 注入模板操作实例 ...

  4. Spring Data Redis入门示例:Hash操作(七)

    将对象存为Redis中的hash类型,可以有两种方式,将每个对象实例作为一个hash进行存储,则实例的每个属性作为hash的field:同种类型的对象实例存储为一个hash,每个实例分配一个field ...

  5. Spring Data Redis 详解及实战一文搞定

    SDR - Spring Data Redis的简称. Spring Data Redis提供了从Spring应用程序轻松配置和访问Redis的功能.它提供了与商店互动的低级别和高级别抽象,使用户免受 ...

  6. Spring Data Redis 让 NoSQL 快如闪电(2)

    [编者按]本文作者为 Xinyu Liu,文章的第一部分重点概述了 Redis 方方面面的特性.在第二部分,将介绍详细的用例.文章系国内 ITOM 管理平台 OneAPM 编译呈现. 把 Redis ...

  7. Spring Data Redis 让 NoSQL 快如闪电 (1)

    [编者按]本文作者为 Xinyu Liu,详细介绍了 Redis 的特性,并辅之以丰富的用例.在本文的第一部分,将重点概述 Redis 的方方面面.文章系国内 ITOM 管理平台 OneAPM 编译呈 ...

  8. Spring Boot使用Spring Data Redis操作Redis(单机/集群)

    说明:Spring Boot简化了Spring Data Redis的引入,只要引入spring-boot-starter-data-redis之后会自动下载相应的Spring Data Redis和 ...

  9. Redis与Spring Data Redis

    1.Redis概述 1.1介绍 官网:https://redis.io/ Redis是一个开源的使用ANSIC语言编写.支持网络.可基于内存 亦可持久化的日志型.Key-Value型的高性能数据库. ...

随机推荐

  1. 384. Shuffle an Array数组洗牌

    [抄题]: Shuffle a set of numbers without duplicates. Example: // Init an array with set 1, 2, and 3. i ...

  2. mysql解压缩版安装方法以及mysql无法启动1067错误

    https://jingyan.baidu.com/article/f3ad7d0ffc061a09c3345bf0.html我下载的版本号是5.6.421.解压到C:\Program Files\M ...

  3. js原生的节点操作API

    // yi获取元素节点 //一 :过id的方式( 通过id查找元素,大小写敏感,如果有多个id只找到第一个) document.getElementById('div1'); // 通过类名查找元素, ...

  4. leveldb 学习记录(五)SSTable格式介绍

    本节主要记录SSTable的结构 为下一步代码阅读打好基础,考虑到已经有大量优秀博客解析透彻 就不再编写了 这里推荐 https://blog.csdn.net/tankles/article/det ...

  5. cpp 区块链模拟示例(五) 序列化

    有了区块和区块链的基本结构,有了工作量证明,我们已经可以开始挖矿了.剩下就是最核心的功能-交易,但是在开始实现交易这一重大功能之前,我们还要预先做一些铺垫,比如数据的序列化和启动命令解析. 根据< ...

  6. .NET winform播放音频文件

    前提:最近要求做一个在winform端做一个音频文件播放的功能,至此,总结最近搜寻的相关资料. 一.微软提供了三种方式来播放音频文件 1.通过System.Media.SoundPlayer来播放 2 ...

  7. Hiberbate注解

    JPA:出现后,所有的ORM框架都有@注解  ,在所有的ORM框架里面是通用的,因此一般是建议大家使用注解进行配置. 实体类一般都有唯一属性,普通属性,集合属性 如何体现ORM思想的? @Entity ...

  8. InternalResourceViewResolver视图解析器(转)

    转载地址:https://www.cnblogs.com/liruiloveparents/p/5054605.html springmvc在处理器方法中通常返回的是逻辑视图,如何定位到真正的页面,就 ...

  9. 背水一战 Windows 10 (81) - 全球化

    [源码下载] 背水一战 Windows 10 (81) - 全球化 作者:webabcd 介绍背水一战 Windows 10 之 全球化 Demo 格式化数字 示例1.演示全球化的基本应用Locali ...

  10. hotmail 收不到邮件的问题

    之前用 hotmail 注册过一个 aws 账号,起了一个 ec2 的免费一年的 VPS,然后没怎么用,不久就把这事忘了. 直到有一天手机收到信用卡扣款消息,我就马上去登账号,却怎么也想不起密码来了, ...