SpringBoot开发二十四-Redis入门以及Spring整合Redis
需求介绍
安装 Redis,熟悉 Redis 的命令以及整合Redis,在Spring 中使用Redis。
代码实现
Redis 内置了 16 个库,索引是 0-15 ,默认选择第 0 个
Redis 的常用命令:
// 切换到第 1 个库
select 1
// 刷新一个库
flushdb
// 查看这个数据库里面有哪些key
Keys * String 类型数据的操作:
// 设置key的值
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 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
然后需要对 Redis 进行配置,要在配置文件 application.properties 里面配置数据库的参数。
# RedisProperties
spring.redis.database=11
spring.redis.host=localhost
spring.redis.port=6379
然后要编写配置类来构造RedisTemplate。其实呢SpringBoot 也对Redis进行了配置RedisTemplate,但是由于Redis是一个key-value的数据库,它在做的时候把key配置成了Object类型,但是由于我们一般都用String,所以重新配置一下。
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; @Configuration
public class RedisConfig {
// 我们要通过 Template 访问数据库,那么它要想具备访问数据库的能力就要能创建连接,而连接又是由连接工厂创建的,所以要把连接工厂注入进来
@Bean
public RedisTemplate<String, Object> redisTemplate(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;
}
}
然后访问数据的时候就是以下用法:
redisTemplate.opsForValue(); // 访问String
redisTemplate.opsForHash(); // 访问Hash
redisTemplate.opsForList(); // 访问List
redisTemplate.opsForSet(); // 访问Set
redisTemplate.opsForZSet(); // 访问ZSet
现在就可以通过 RedisTemplate 来访问Redis数据库,来添加删除数据。
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的更多相关文章
- SpringBoot开发二十-Redis入门以及Spring整合Redis
安装 Redis,熟悉 Redis 的命令以及整合Redis,在Spring 中使用Redis. 代码实现 Redis 内置了 16 个库,索引是 0-15 ,默认选择第 0 个 Redis 的常用命 ...
- 二十六:Struts2 和 spring整合
二十六:Struts2 和 spring整合 将项目名称为day29_02_struts2Spring下的scr目录下的Struts.xml文件拷贝到新项目的scr目录下 在新项目的WebRoot-- ...
- (十四)mybatis 和 spring 整合
目录 整合思想 整合步骤 整合之后原始 dao 开发 整合之后 Mapper 代理开发 总结 整合思想 让 spring 管理 sqlSessionFactory ,使用 单例模式 创建该对象 : 根 ...
- SpringBoot开发二十二-统一处理异常
需求介绍 首先服务端分为三层:表现层,业务层,数据层. 请求过来先到表现层,表现层调用业务层,然后业务层调用数据层. 那么数据层出现异常它会抛出异常,那异常肯定是抛给调用者也就是业务层,那么业务层会再 ...
- SpringBoot开发二十-私信列表
私信列表功能开发. 发送私信功能开发 首先创建一个实体类:Message package com.nowcoder.community.entity; import java.util.Date; p ...
- python运维开发(二十四)----crm权限管理系统
内容目录: 数据库设计 easyUI的使用 数据库设计 权限表Perssion 角色表Role 权限和角色关系表RoleToPermission 用户表UserInfo 用户和角色关系表UserInf ...
- Jmeter(二十四) - 从入门到精通 - JMeter函数 - 中篇(详解教程)
1.简介 在性能测试中为了真实模拟用户请求,往往我们需要让提交的表单内容每次都发生变化,这个过程叫做参数化.JMeter配置元件与前置处理器都能帮助我们进行参数化,但是都有局限性,为了帮助我们能够更好 ...
- Bootstrap入门(二十四)data属性
Bootstrap入门(二十四)data属性 你可以仅仅通过 data 属性 API 就能使用所有的 Bootstrap 插件,无需写一行 JavaScript 代码.这是 Bootstrap 中的一 ...
- python3.4学习笔记(二十四) Python pycharm window安装redis MySQL-python相关方法
python3.4学习笔记(二十四) Python pycharm window安装redis MySQL-python相关方法window安装redis,下载Redis的压缩包https://git ...
随机推荐
- Postman团队协作开发
介绍 Postman是一款强大的API开发调试软件,它跨平台(真正跨平台,支持linux/mac os/windows),同时还提供浏览器插件,可以说是一个良心软件, 今天主要说一下Postman团队 ...
- python base64(图片)编码
参考:https://blog.csdn.net/Good_Luck_Kevin2018/article/details/80953312 通常会在网页中遇到用src="data:image ...
- pip 下载时出现问题TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'
我这里解决就是更新下载源,马德,中科的源居然不够快,我就只能换源了,一换就成功了 1.一次性(临时使用): 可以在使用pip的时候加参数-i https://pypi.tuna.tsinghua.ed ...
- ROS2学习之旅(12)——创建工作空间
workspace(工作空间)是包含ROS2 packages(包)的文件夹.在使用ROS 2之前,有必要在终端中source一下ROS 2的安装工作区,这样就可以在该终端中使用ROS 2的软件包. ...
- postgresql行列转换
--安装扩展 CREATE EXTENSION tablefunc --使用CROSSTAB函数 SELECT * FROM CROSSTAB('SELECT 主键, 需转换的列名, 需转换的列值 F ...
- Anaconda软件安装使用问题
目录 更新源 用conda安装包出现的环境不一致问题 更新源 命令行 conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/ ...
- 「NOIP2017」宝藏
「NOIP2017」宝藏 题解 博客阅读效果更佳 又到了一年一度NOIPCSP-S 赛前复习做真题的时间 于是就遇上了这道题 首先观察数据范围 \(1 \le n \le 12\) ,那么极大可能性是 ...
- 前端-HTML基础+CSS基础
.pg-header { height: 48px; text-align: center; line-height: 48px; background-color: rgba(127, 255, 2 ...
- 二进制方式安装 k8s
推荐个好用的安装k8s的工具 https://github.com/easzlab/kubeasz 该工具基于二进制方式部署 k8s, 利用 ansible-playbook 实现自动化 1.1 ...
- 微信小程序创建第一个项目
一.打开微信开发者工具,扫码登录 二.点击右侧的加号,添加小程序 第三步:创建成功后,报错 VM82:1 cloud init error: Error: invalid scope 没有权限,请先开 ...