安装 Redis,熟悉 Redis 的命令以及整合Redis,在Spring 中使用Redis。

代码实现

Redis 内置了 16 个库,索引是 0-15 ,默认选择第 0 个

Redis 的常用命令:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

select 1

flushdb

Keys *

String 类型数据的操作:

set k1 1
// 获得key的值
get k1
// 删除key的值
del k1
// 对key值自增自减
incr k1
decr k1

hash 类型数据的操作:
// 设置key的值
格式是:hset hash的key 项的key 项的值
例如:hset myhash id 1
// 设置多对key值
格式是:hmset hash的key 项的key 项的值
例如:hmset myhash id 1 name xixi
// 获取key的值
格式是:hget hash的key 项的key
例如:hget myhash id
// 获取多对key的值
格式是:hmget hash的key 项的key
例如:hmget myhash id name
// 获取该key下所有的值
格式是:hgetall hash的key
例如:hgetall myhash
// 如果项不存在则赋值,存在时什么都不做
格式是:hsetnx Hash的key 项的key 项的值
例如:hsetnx myhash address earth
// 判断键值是否存在
格式是:hexists hash的key 项的key
例如:hexists myhash id

Spring 引入 Redis

首先要在 pom.xml 引入依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

然后需要对 Redis 进行配置,要在配置文档 application.properties 里面配置数据库的参数。

1
2
3
4
# RedisProperties
spring.redis.database=11
spring.redis.host=localhost
spring.redis.port=6379

然后要编写配置类来构造RedisTemplate。其实呢SpringBoot 也对Redis进行了配置RedisTemplate,但是由于Redis是一个key-value的数据库,它在做的时候把key配置成了Object类型,但是由于我们一般都用String,所以重新配置一下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.nowcoder.community.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

public class {
// 我们要通过 Template 访问数据库,那么它要想具备访问数据库的能力就要能创建连接,而连接又是由连接工厂创建的,所以要把连接工厂注入进来

public RedisTemplate<String, Object> (RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 使得Template有访问数据库的能力
template.setConnectionFactory(redisConnectionFactory);

// 设置key的序列化的方式
template.setKeySerializer(RedisSerializer.string());
// 设置value的序列化方式
template.setValueSerializer(RedisSerializer.json());
// 设置hash的key的序列化的方式
template.setHashKeySerializer(RedisSerializer.string());
// 设置hash的value的序列化的方式
template.setHashValueSerializer(RedisSerializer.json());

template.afterPropertiesSet();
return template;
}
}

然后访问数据的时候就是以下用法:

1
2
3
4
5
redisTemplate.opsForValue(); // 访问String
redisTemplate.opsForHash(); // 访问Hash
redisTemplate.opsForList(); // 访问List
redisTemplate.opsForSet(); // 访问Set
redisTemplate.opsForZSet(); // 访问ZSet

现在就可以通过 RedisTemplate 来访问Redis数据库,来添加删除数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
10 大专栏  SpringBoot开发二十-Redis入门以及Spring整合Redis6
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package com.nowcoder.community;

import org.aspectj.lang.annotation.Aspect;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.TimeUnit;

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class RedisTests {
@Autowired
private RedisTemplate redisTemplate;

@Test
public void testStrings() {
String redisKey = "test:count";
redisTemplate.opsForValue().set(redisKey, 1);
System.out.println(redisTemplate.opsForValue().get(redisKey));
System.out.println(redisTemplate.opsForValue().increment(redisKey));
System.out.println(redisTemplate.opsForValue().decrement(redisKey));
}

@Test
public void testHashes() {
String redisKey = "test:user";

redisTemplate.opsForHash().put(redisKey, "id", 1);
redisTemplate.opsForHash().put(redisKey, "username", "zhangsan");

System.out.println(redisTemplate.opsForHash().get(redisKey, "id"));
System.out.println(redisTemplate.opsForHash().get(redisKey, "username"));
}

@Test
public void testLists() {
String redisKey = "test:ids";

redisTemplate.opsForList().leftPush(redisKey, 101);
redisTemplate.opsForList().leftPush(redisKey, 102);
redisTemplate.opsForList().leftPush(redisKey, 103);

System.out.println(redisTemplate.opsForList().size(redisKey));
System.out.println(redisTemplate.opsForList().index(redisKey, 0));
System.out.println(redisTemplate.opsForList().range(redisKey, 0, 2));

// 从左边弹出,左边leftpop,右边rightpop
System.out.println(redisTemplate.opsForList().leftPop(redisKey));
System.out.println(redisTemplate.opsForList().leftPop(redisKey));
System.out.println(redisTemplate.opsForList().leftPop(redisKey));
}

@Test
public void testSets() {
String redisKey = "test:teachers";

redisTemplate.opsForSet().add(redisKey, "刘备", "关羽", "张飞", "赵云", "诸葛亮");

System.out.println(redisTemplate.opsForSet().size(redisKey));
System.out.println(redisTemplate.opsForSet().pop(redisKey));
System.out.println(redisTemplate.opsForSet().members(redisKey));
}

@Test
public void testSortedSets() {
String redisKey = "test:students";

redisTemplate.opsForZSet().add(redisKey, "唐僧", 80);
redisTemplate.opsForZSet().add(redisKey, "悟空", 90);
redisTemplate.opsForZSet().add(redisKey, "八戒", 50);
redisTemplate.opsForZSet().add(redisKey, "沙僧", 70);
redisTemplate.opsForZSet().add(redisKey, "白龙马", 60);

// 统计数据
System.out.println(redisTemplate.opsForZSet().zCard(redisKey));
// 查询某个人的分数
System.out.println(redisTemplate.opsForZSet().score(redisKey, "八戒"));
// 查询排名,默认从小到大
System.out.println(redisTemplate.opsForZSet().reverseRank(redisKey, "八戒"));
// 查询区间排名数据
System.out.println(redisTemplate.opsForZSet().reverseRange(redisKey, 0, 2));
}

@Test
public void testKeys() {
redisTemplate.delete("test:user");

System.out.println(redisTemplate.hasKey("test:user"));

redisTemplate.expire("test:students", 10, TimeUnit.SECONDS);
}

// 多次访问同一个key
@Test
public void testBoundOperations() {
String redisKey = "test:count";
BoundValueOperations operations = redisTemplate.boundValueOps(redisKey);
operations.increment();
operations.increment();
operations.increment();
operations.increment();
operations.increment();
System.out.println(operations.get());
}

// Redis编程序事务,并不一定满足我们之前说过的事务,因为不是关系型数据库
@Test
public void testTransactional() {
Object obj = redisTemplate.execute(new SessionCallback() {
@Override
public Object execute(RedisOperations operations) throws DataAccessException {
String redisKey = "test:tx";
// 启用事务
operations.multi();

operations.opsForSet().add(redisKey, "zhangsan");
operations.opsForSet().add(redisKey, "lisi");
operations.opsForSet().add(redisKey, "wangwu");

System.out.println(operations.opsForSet().members(redisKey));
// 提交事务
return operations.exec();
}
});
System.out.println(obj);
}
}

SpringBoot开发二十-Redis入门以及Spring整合Redis的更多相关文章

  1. SpringBoot开发二十四-Redis入门以及Spring整合Redis

    需求介绍 安装 Redis,熟悉 Redis 的命令以及整合Redis,在Spring 中使用Redis. 代码实现 Redis 内置了 16 个库,索引是 0-15 ,默认选择第 0 个 Redis ...

  2. SpringBoot开发二十二-统一处理异常

    需求介绍 首先服务端分为三层:表现层,业务层,数据层. 请求过来先到表现层,表现层调用业务层,然后业务层调用数据层. 那么数据层出现异常它会抛出异常,那异常肯定是抛给调用者也就是业务层,那么业务层会再 ...

  3. SpringBoot开发二十-私信列表

    私信列表功能开发. 发送私信功能开发 首先创建一个实体类:Message package com.nowcoder.community.entity; import java.util.Date; p ...

  4. python3.4学习笔记(二十四) Python pycharm window安装redis MySQL-python相关方法

    python3.4学习笔记(二十四) Python pycharm window安装redis MySQL-python相关方法window安装redis,下载Redis的压缩包https://git ...

  5. 设计模式学习(二十四):Spring 中使用到的设计模式

    设计模式学习(二十四):Spring 中使用到的设计模式 作者:Grey 原文地址: 博客园:设计模式学习(二十四):Spring 中使用到的设计模式 CSDN:设计模式学习(二十四):Spring ...

  6. 网站性能优化小结和spring整合redis

    现在越来越多的地方需要非关系型数据库了,最近网站优化,当然从页面到服务器做了相应的优化后,通过在线网站测试工具与之前没优化对比,发现有显著提升. 服务器优化目前主要优化tomcat,在tomcat目录 ...

  7. Spring整合Redis&JSON序列化&Spring/Web项目部署相关

    几种JSON框架用法和效率对比: https://blog.csdn.net/sisyphus_z/article/details/53333925 https://blog.csdn.net/wei ...

  8. Spring整合redis实现key过期事件监听

    打开redis服务的配置文件   添加notify-keyspace-events Ex  如果是注释了,就取消注释 这个是在以下基础上进行添加的 Spring整合redis:https://www. ...

  9. redis入门(15)redis的数据备份和恢复

    redis入门(15)redis的数据备份和恢复

随机推荐

  1. csv文件——简单读操作01

    转载:https://www.py.cn/spider/advanced/14381.html import csv with open('C:\\Users\\del\\Desktop\\123.c ...

  2. CAR-T|Single cell plan|Extracellular RNA|

    生物医疗大数据 安吉丽娜朱莉发现抑癌基因事件,BRCA突变与乳腺癌关联. 个体化测序商品23 and me 多组学数据研究:eg:太空和地球双胞胎发现生化指标差不多. 研究模式和工业模式相结合. 研究 ...

  3. springboot跨域请求接口示例

    一.项目架构 二.项目内容 1.GlobalCrosConfig.java package com.config; import org.springframework.context.annotat ...

  4. GUI(Graphical User Interface)

    译:用户和图形界面 GUI与程序交互的不同方式,包含3基本要素:输入,处理和输出. 常用GUI框架包括以下几种: wxPython Kivy Flexx PyQt Tkinter Pywin32 Py ...

  5. zip4j 2.0压缩 加密压缩

    https://github.com/srikanth-lingala/zip4j ZipParameters zipParameters = new ZipParameters(); zipPara ...

  6. Juniper srx新增接口IP,使PC直连srx(转)

    转自:https://www.jianshu.com/p/bc27134bde3d Juniper srx新增接口IP,使PC直连srx 2018.11.19 14:24:15字数 424 概述 需求 ...

  7. 第一行代码新闻例子报错 Unable to start activity ComponentInfo 原因

    E/AndroidRuntime: FATAL EXCEPTION: main Process: com.timemanager.jason.fragmentbestpractice, PID: 56 ...

  8. git 推送到github最常用命令

    初始化仓库,上传到github中. git init git add README.md git commit -m "first commit" git remote add o ...

  9. 使用tcpdump查看HTTP请求响应 详细信息 数据

    安装tcpdump: sudo yum install tcpdump 查看get请求: tcpdump -s 0 -A 'tcp dst port 80 and tcp[((tcp[12:1] &a ...

  10. Python笔记_第三篇_面向对象_2.构造函数和析构函数(含self说明)

    1. 构造函数: 为什么要有构造函数? 打一个比方:类的创建就是好比你创建了好了一种格式的房间,你租给上一个住户的后,里面会对方很多“垃圾”和不规则的物品摆放.构造函数就是下一个住户再使用的时候进行物 ...