5.1 Jedis连接Redis
5.1.1 创建Maven工程
idea创建
5.1.2 导入需要的依赖
<dependencies>
<!-- 1、 Jedis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!-- 2、 Junit测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- 3、 Lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
</dependency>
</dependencies>
5.1.3 测试
public class Demo1 {
@Test
public void set(){
//1. 连接Redis
Jedis jedis = new Jedis("192.168.199.109",6379);
//2. 操作Redis - 因为Redis的命令是什么,Jedis的方法就是什么
jedis.set("name","李四");
//3. 释放资源
jedis.close();
}
@Test
public void get(){
//1. 连接Redis
Jedis jedis = new Jedis("192.168.199.109",6379);
//2. 操作Redis - 因为Redis的命令是什么,Jedis的方法就是什么
String value = jedis.get("name");
System.out.println(value);
//3. 释放资源
jedis.close();
}
}
5.2 Jedis存储一个对象到Redis以byte[]的形式
5.2.1 准备一个User实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
private Integer id;
private String name;
private Date birthday;
}
5.2.2 导入spring-context依赖
<!-- 4. 导入spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
5.2.3 创建Demo测试类,编写内容
public class Demo2 {
// 存储对象 - 以byte[]形式存储在Redis中
@Test
public void setByteArray(){
//1. 连接Redis服务
Jedis jedis = new Jedis("192.168.199.109",6379);
//------------------------------------------------
//2.1 准备key(String)-value(User)
String key = "user";
User value = new User(1,"张三",new Date());
//2.2 将key和value转换为byte[]
byte[] byteKey = SerializationUtils.serialize(key);
byte[] byteValue = SerializationUtils.serialize(value);
//2.3 将key和value存储到Redis
jedis.set(byteKey,byteValue);
//------------------------------------------------
//3. 释放资源
jedis.close();
}
// 获取对象 - 以byte[]形式在Redis中获取
@Test
public void getByteArray(){
//1. 连接Redis服务
Jedis jedis = new Jedis("192.168.199.109",6379);
//------------------------------------------------
//2.1 准备key
String key = "user";
//2.2 将key转换为byte[]
byte[] byteKey = SerializationUtils.serialize(key);
//2.3 jedis去Redis中获取value
byte[] value = jedis.get(byteKey);
//2.4 将value反序列化为User对象
User user = (User) SerializationUtils.deserialize(value);
//2.5 输出
System.out.println("user:" + user);
//------------------------------------------------
//3. 释放资源
jedis.close();
}
}
5.3 Jedis存储一个对象到Redis以String的形式
5.3.1 导入依赖
<!-- 导入fastJSON -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
5.3.2 测试
public class Demo3 {
// 存储对象 - 以String形式存储
@Test
public void setString(){
//1. 连接Redis
Jedis jedis = new Jedis("192.168.199.109",6379);
//2.1 准备key(String)-value(User)
String stringKey = "stringUser";
User value = new User(2,"李四",new Date());
//2.2 使用fastJSON将value转化为json字符串
String stringValue = JSON.toJSONString(value);
//2.3 存储到Redis中
jedis.set(stringKey,stringValue);
//3. 释放资源
jedis.close();
}
// 获取对象 - 以String形式获取
@Test
public void getString(){
//1. 连接Redis
Jedis jedis = new Jedis("192.168.199.109",6379);
//2.1 准备一个key
String key = "stringUser";
//2.2 去Redis中查询value
String value = jedis.get(key);
//2.3 将value反序列化为User
User user = JSON.parseObject(value, User.class);
//2.4 输出
System.out.println("user:" + user);
//3. 释放资源
jedis.close();
}
}
5.4 Jedis连接池的操作
使用连接池操作Redis,避免频繁创建和销毁链接对象消耗资源
@Test
public void pool2(){
//1. 创建连接池配置信息
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxTotal(100); // 连接池中最大的活跃数
poolConfig.setMaxIdle(10); // 最大空闲数
poolConfig.setMinIdle(5); // 最小空闲数
poolConfig.setMaxWaitMillis(3000); // 当连接池空了之后,多久没获取到Jedis对象,就超时
//2. 创建连接池
JedisPool pool = new JedisPool(poolConfig,"192.168.199.109",6379);
//3. 通过连接池获取jedis对象
Jedis jedis = pool.getResource();
//4. 操作
String value = jedis.get("stringUser");
System.out.println("user:" + value);
//5. 释放资源
jedis.close();
}
5.5 Redis的管道操作
因为在操作Redis的时候,执行一个命令需要先发送请求到Redis服务器,这个过程需要经历网络的延迟,Redis还需要给客户端一个响应。
如果我需要一次性执行很多个命令,上述的方式效率很低,可以通过Redis的管道,先将命令放到客户端的一个Pipeline中,之后一次性的将全部命令都发送到Redis服务,Redis服务一次性的将全部的返回结果响应给客户端。
// Redis管道的操作
@Test
public void pipeline(){
//1. 创建连接池
JedisPool pool = new JedisPool("192.168.199.109",6379);
long l = System.currentTimeMillis();
/*//2. 获取一个连接对象
Jedis jedis = pool.getResource();
//3. 执行incr - 100000次
for (int i = 0; i < 100000; i++) {
jedis.incr("pp");
}
//4. 释放资源
jedis.close();*/
//================================
//2. 获取一个连接对象
Jedis jedis = pool.getResource();
//3. 创建管道
Pipeline pipelined = jedis.pipelined();
//3. 执行incr - 100000次放到管道中
for (int i = 0; i < 100000; i++) {
pipelined.incr("qq");
}
//4. 执行命令
pipelined.syncAndReturnAll();
//5. 释放资源
jedis.close();
System.out.println(System.currentTimeMillis() - l);
}
5.6 Redis的应用
5.6.1 准备开放平台项目
在资料资料中
5.6.2 准备docker-compose.yml文件
# docker-compose.yml
version: "3.1"
services:
nginx:
image: daocloud.io/library/nginx:latest
restart: always
container_name: nginx
ports:
- 80:80
volumes:
- ./nginx_conf:/etc/nginx/conf.d
tomcat1:
image: daocloud.io/library/tomcat:8.5.15-jre8
restart: always
container_name: tomcat1
ports:
- 8081:8080
environment:
- TZ=Asia/Shanghai
volumes:
- ./tomcat1_webapps:/usr/local/tomcat/webapps
tomcat2:
image: daocloud.io/library/tomcat:8.5.15-jre8
restart: always
container_name: tomcat2
ports:
- 8082:8080
environment:
- TZ=Asia/Shanghai
volumes:
- ./tomcat2_webapps:/usr/local/tomcat/webapps
mysql:
image: daocloud.io/library/mysql:5.7.24
restart: always
container_name: mysql
ports:
- 3306:3306
environment:
- MYSQL_ROOT_PASSWORD=root
- TZ=Asia/Shanghai
volumes:
- ./mysql_data:/var/lib/mysql
command:
--lower_case_table_names=1 # 忽略表名的大小写
5.6.3 部署项目到Tomcat容器中
打成war包,复制到数据卷路径中即可
5.6.4 修改认证功能
//登录 Controller
@RequestMapping("/dologin")
@ResponseBody
public AjaxMessage login(String email, String password, HttpSession session,HttpServletResponse resp) {
//1. 调用service执行认证,返回Redis的key
String key = adminUserService.doLoginByRedis(email,password);
//2. 判断返回的key是否为null
if(StringUtils.isEmpty(key)) {
//2.1 如果为null -> 认证失败
return new AjaxMessage(false);
}
//3. 查询用户的权限信息,并且放到Redis中
menuService.setUserMenuList(key);
//4. 将key作为Cookie写回浏览器端
Cookie cookie = new Cookie(AdminConstants.USER_COOKIE_KEY,key);
cookie.setPath("/");
cookie.setMaxAge(9999999);
resp.addCookie(cookie);
//5. 返回认证成功信息
return new AjaxMessage(true);
}
//AdminUserService实现认证功能
@Override
public String doLoginByRedis(String email, String password) throws JsonProcessingException {
//1. 判断用户名和密码是否正确
AdminUser user = adminUserMapper.getUserByEmail(email);
//2. 如果user==null , 登录失败,返回null
if(user == null){
return null;
}
//3. user != null 登录成功,声明一个UUID,作为存储到Redis中的key,返回key到Controller
//3.1 声明key和value
String key = UUID.randomUUID().toString();
ObjectMapper mapper = new ObjectMapper();
String value = mapper.writeValueAsString(user);
//3.2 将key和value存储到Redis中
Jedis jedis = pool.getResource();
jedis.setex(AdminConstants.SESSION_USER + key,600,value);
jedis.close();
//4. 返回结果
return key;
}
//MenuService将用户的权限信息存储到Redis中
@Override
public void setUserMenuList(String key) throws JsonProcessingException {
//1. 获取用户的id
Jedis jedis = pool.getResource();
String value = jedis.get(AdminConstants.SESSION_USER + key);
ObjectMapper mapper = new ObjectMapper();
AdminUser adminUser = mapper.readValue(value, AdminUser.class);
//2. 数据库查询用户权限信息
List<Menu> menuList = menuMapper.getUserMenu(adminUser.getId());
//3. 存储到Redis
String menuKey = AdminConstants.USER_MENU + key;
String menuValue = mapper.writeValueAsString(menuList);
jedis.setex(menuKey,600,menuValue);
jedis.close();
}
5.6.5 修改过滤器信息
//在filter中获取Jedis连接池的方式
private JedisPool pool;
public void init(FilterConfig filterConfig) throws ServletException {
ServletContext servletContext = filterConfig.getServletContext();
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
pool = (JedisPool) context.getBean("jedisPool");
}
// 修改doFilter方法
// 获取认证信息
String key = null;
// 获取Cookie
Cookie[] cookies = request.getCookies();
if(cookies != null){
for (Cookie cookie : cookies) {
if(cookie.getName().equals(AdminConstants.USER_COOKIE_KEY)){
key = cookie.getValue();
}
}
}
// 没有认证过,cookie中没有获取到指定的信息
if(key == null){
response.sendRedirect(request.getContextPath() + redirectUrl);
return;
}
// 从Session域中获取用户认证信息
// AdminUser user = (AdminUser) session.getAttribute(AdminConstants.SESSION_USER);
// 修改为从Redis中获取用户的信息
Jedis jedis = pool.getResource();
String value = jedis.get(AdminConstants.SESSION_USER + key);
if (value == null) {
jedis.close();
response.sendRedirect(request.getContextPath() + redirectUrl);
return;
}
// ...
//2.2 获取权限信息
// 从Session中获取了用户的权限信息
String menuValue = jedis.get(AdminConstants.USER_MENU + key);
// 重置key的生存时间
jedis.expire(AdminConstants.SESSION_USER + key,600);
jedis.expire(AdminConstants.USER_MENU + key,600);
jedis.close();
ObjectMapper mapper = new ObjectMapper();
List<Menu> menus = mapper.readValue(menuValue, new TypeReference<List<Menu>>() {});
5.6.6 修改SystemController
@RequestMapping("/side")
@ResponseBody
public AjaxMessage getMenuTree(@CookieValue(value = AdminConstants.USER_COOKIE_KEY,required = false)String key, HttpSession session, HttpServletResponse response) throws JsonProcessingException {
// 修改AdminUser user = (AdminUser) session.getAttribute(AdminConstants.SESSION_USER);
Jedis jedis = pool.getResource();
String value = jedis.get(AdminConstants.SESSION_USER + key);
ObjectMapper mapper = new ObjectMapper();
AdminUser user = mapper.readValue(value, AdminUser.class);
if (user == null) {
try {
response.sendRedirect("/login.html");
} catch (IOException e) {
e.printStackTrace();
}
return new AjaxMessage(true, null, new ArrayList<>());
}
jedis.expire(AdminConstants.SESSION_USER + key,600);
jedis.close();
List<Menu> menus = menuService.getUserPermission(user.getId());
return new AjaxMessage(true, null, menus);
}
5.6.7 重新部署
重新打成war包,复制到数据卷路径中即可
5.7 Redis 和 Springboot
5.7.1 创建springboot项目加入依赖
pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
或者在创建时直接选择加入
5.7.2 修改redis的 docker-compose.yml配置文件设置redis.conf的数据券映射
version: '3.1'
services:
redis:
image: daocloud.io/library/redis:5.0.7
restart: always
container_name: redis
environment:
- TZ=Asia/Shanghai
ports:
- 6379:6379
volumes:
- ./conf/redis.conf:/usr/local/redis/redis.conf
command: ["redis-server","/usr/local/redis/redis.conf"]
ps:
1.注意在启动前,先手动创建对应的conf目录及redis.conf文件,防止docker把redis.conf配置文件当成目录看待
2.先把之前的redis容器停止并删除,使用docker-compose重新启动
5.7.3 redis.conf配置文件
1.复制一个redis.conf的文件去覆盖之前占位置用的redis.conf空文件
2.修改redis.conf配置文件
一,要解除只允许本机访问的设置
二,要设置远程访问保护(关闭)
一,要解除只允许本机访问的设置
二,要设置远程访问保护(关闭)
重启redis服务器
5.7.4 配置springboot yml配置文件
spring:
redis:
port: 6379 #可以不写,默认就是6379
database: 0 #默认值就是0,redis的库有16个,0-15,默认选用0号,注意各个库的数据不相同
host: 192.168.116.128 #默认值为localhost的本地,需要修改为linux的ip
5.7.5 在test当中进行测试
@SpringBootTest
class RedisQf2111ApplicationTests {
//jdk 使用jdk进行序列化处理 ,中文等字符会变成'\xe6'这种编码,但不影响使用,只是在redis数据库中直接看到这样
@Autowired
private RedisTemplate redisTemplate;
//使用字符串进行序列化处理,中文等等的字符是不会有变化,但是key和value都必须是字符串的形式存入
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
void t1() {
//boundValueOps(key) 这个设置简单的key-value =>redis中的string数据类型
try {
// set(值) 这个是设值的方法 2个一起就是 redis中的 set key value命令
stringRedisTemplate.boundValueOps("name").set("张三");
} catch (Exception e) {
e.printStackTrace();
}
}
}
5.7.6 string类型的操作
@Autowired
private StringRedisTemplate stringRedisTemplate;
//存值
stringRedisTemplate.boundValueOps("key").set("value");
//取值
String val = stringRedisTemplate.boundValueOps("key").get();
//获取字符串长度
long num = stringRedisTemplate.boundValueOps("admin").size();
//默认自增1 redis返回出来的num最新的值
Long num = stringRedisTemplate.boundValueOps("num").increment();
//设置 自定义的自增数 redis返回出来的num最新的值
Long num2 = stringRedisTemplate.boundValueOps("num").increment(5);
//默认的自减1 redis返回出来的num最新的值
Long num3 = stringRedisTemplate.boundValueOps("num").decrement();
//设置 自定义的自减数 redis返回出来的num最新的值
Long num4 = stringRedisTemplate.boundValueOps("num").decrement(3);
//相当于 redis setnx的命令
Boolean ans = redisTemplate.boundValueOps("ename").setIfAbsent("李四");
// redis append命令 返回的数值 这个值最新的字符串长度
//注意redis本身不支持中文等等的字符,在redis保存为\xac\xed\x00\x05t\x00,所以出现计数的数值问题
Integer append = stringRedisTemplate.boundValueOps("ename").append("哈哈");
//key admin value zhangshang
// redis 2种 秒 毫秒
// 1 TimeUnit.SECONDS 1秒 过期
// 1 TimeUnit.HOURS 1小时 过期
// 1 TimeUnit.MILLISECONDS 1毫秒 过期
// 1 TimeUnit.DAYS 1天 过期
stringRedisTemplate.boundValueOps("admin").set("zhangshang",200, TimeUnit.SECONDS);
//getExpire 返回的是以秒为单位的剩余时间
Long admin = stringRedisTemplate.boundValueOps("admin").getExpire();
//expire 重设 生存时间
tringRedisTemplate.boundValueOps("admin").expire(1, TimeUnit.DAYS);
//删除 key
Boolean admin = stringRedisTemplate.delete("admin");
示例
@SpringBootTest
class RedisQf2111ApplicationTests {
/*
这些序列化规则的数据是不共通,简单理解,1个是吧中文翻译为英文,一个是翻译为日语
使用redisTemplate来存储数据,就必须使用redisTemplate来取值,不能使用stringRedisTemplate来取,容易出现数据错误问题
*/
//jdk 使用jdk进行序列化处理 ,中文等字符会变成'\xe6'这种编码,但不影响使用,只是在redis数据库中直接看到这样
@Autowired
private RedisTemplate redisTemplate;
//使用字符串进行序列化处理,中文等等的字符是不会有变化,但是key和value都必须是字符串的形式存入
@Autowired
private StringRedisTemplate stringRedisTemplate;
//设置redistemplate 类在里面进行打蜡的api的方法封装, 去掉方法的差异化
/**
*
* @author: COS
* @return:
* @time: 2022/4/15 10:37
* @description: 使用 string数据类型进行存值
*/
@Test
void t1() {
//jedis j = new Jedis("ip","端口")
//j.set("")
//j.get();
//boundValueOps(key) 这个设置简单的key-value =>redis中的string数据类型
try {
// set(值) 这个是设值的方法 2个一起就是 redis中的 set key value命令
stringRedisTemplate.boundValueOps("name").set("张三");
System.out.println("成功");
} catch (Exception e) {
e.printStackTrace();
System.out.println("失败");
}
}
@Test
void t2() {
//get 是取值
String name = stringRedisTemplate.boundValueOps("name").get();
System.out.println(name);
}
@Test
void t3() {
//get 是取值
try {
// key num value 1
stringRedisTemplate.boundValueOps("num").set("1");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @author: COS
* @return:
* @time: 2022/4/15 10:40
* @description: 自增
*/
@Test
void t4() {
try {
// key num value 1
//默认自增1
// Long num = stringRedisTemplate.boundValueOps("num").increment();
//设置 自定义的自增数
//Long num = stringRedisTemplate.boundValueOps("num").increment(5);
//默认的自减1
// Long num = stringRedisTemplate.boundValueOps("num").decrement();
//设置 自定义的自减数
Long num = stringRedisTemplate.boundValueOps("num").decrement(3);
//输出 redis返回出来的num最新的值
System.out.println(num);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
void t5() {
//相当于 redis setnx的命令
// Boolean ans = stringRedisTemplate.boundValueOps("ename").setIfAbsent("李四");
Boolean ans = redisTemplate.boundValueOps("ename").setIfAbsent("李四");
if (ans) {
System.out.println("添加值了");
}else{
System.out.println("没有添加值");
}
}
@Test
void t6() {
// redis append命令 返回的数值 这个值最新的字符串长度
//注意redis本身不支持中文等等的字符,所以在redis
Integer append = stringRedisTemplate.boundValueOps("ename").append("哈哈");
//12=>4
System.out.println(append);
}
/**
*
* @author: COS
* @return:
* @time: 2022/4/15 11:10
* @description: 设置 过期 时间 生存时间
*/
@Test
void t8() {
//key admin value zhangshang
// redis 2种 秒 毫秒
// 1 TimeUnit.SECONDS 1秒 过期
// 1 TimeUnit.HOURS 1小时 过期
// 1 TimeUnit.MILLISECONDS 1毫秒 过期
// 1 TimeUnit.DAYS 1天 过期
try {
stringRedisTemplate.boundValueOps("admin").set("zhangshang",200, TimeUnit.SECONDS);
System.out.println("ok");
} catch (Exception e) {
e.printStackTrace();
System.out.println("no ok");
}
}
/**
*
* @author: COS
* @return:
* @time: 2022/4/15 11:10
* @description: 获取值的剩余生存时间 命令里面ttl
*/
@Test
void t9() {
//getExpire 返回的是以秒为单位的剩余时间
Long admin = stringRedisTemplate.boundValueOps("admin").getExpire();
System.out.println(admin);
}
@Test
void t10() {
//expire 重设 生存时间
stringRedisTemplate.boundValueOps("admin").expire(1, TimeUnit.DAYS);
}
@Test
void t11() {
//删除 key
Boolean admin = stringRedisTemplate.delete("admin");
System.out.println(admin);
}
//取string值用的测试方法
@Test
void getValue() {
/* \01f */
System.out.println(stringRedisTemplate.boundValueOps("admin").get());
// strlen 命令 查看value字符串的长度
System.out.println(stringRedisTemplate.boundValueOps("admin").size());
}
}
5.7.7 hash类型
//存值
stringRedisTemplate.boundHashOps("names").put("first","张");
stringRedisTemplate.boundHashOps("names").put("last", "三");
//去单个值
String o = (String) stringRedisTemplate.boundHashOps("names").get("first");
//使用map一次性存值
Map<String, String> maps = new HashMap<>();
maps.put("age", "18");
maps.put("salary", "12.0");
stringRedisTemplate.boundHashOps("names").putAll(maps);
//获取所有key
Set<Object> names = stringRedisTemplate.boundHashOps("names").keys();
//获取所有value
List<Object> names1 = stringRedisTemplate.boundHashOps("names").values();
// 自增
Long increment = stringRedisTemplate.boundHashOps("names").increment("age", 1);
// 计数有多少个属性在names里面
Long count = stringRedisTemplate.boundHashOps("names").size();
//使用属性名删除
Long delete = stringRedisTemplate.boundHashOps("names").delete("salary", "last");
//hsetnx
Boolean ans = stringRedisTemplate.boundHashOps("names").putIfAbsent("last", "xxxx");
//hexists 判断key是否存在
Boolean ans = stringRedisTemplate.boundHashOps("names").hasKey("last1");
5.7.8 list类型
//查询所有
//range 查询下标范围的值 -1为最后1个值
List<String> hobby = stringRedisTemplate.boundListOps("hobby").range(0, -1);
//获取列表中的所有元素个数
Long count = stringRedisTemplate.boundListOps("hobby").size();
//在列表左边添加数据
Long aLong1 = stringRedisTemplate.boundListOps("hobby").leftPush("读书");
Long aLong2 = stringRedisTemplate.boundListOps("hobby").leftPush("玩游戏");
//在列表右边添加数据
stringRedisTemplate.boundListOps("hobby").rightPush("娃哈哈");
//在下标位置插值
stringRedisTemplate.boundListOps("hobby").set(2,"我试试看看");
//从左边第一个值弹出
String left = stringRedisTemplate.boundListOps("hobby").leftPop();
//从右边第一个值弹出
String right = stringRedisTemplate.boundListOps("hobby").rightPop();
//使用下标取值
String hobby = stringRedisTemplate.boundListOps("hobby").index(1);
5.7.9 set类型
// 添加数据 在set 集合中 可变长参数
Long count = stringRedisTemplate.boundSetOps("star2").add("刘德华", "陈奕迅", "成龙");
// 获取集合中所有数据
Set<String> star = stringRedisTemplate.boundSetOps("star").members();
//交集
Set<String> intersect = stringRedisTemplate.boundSetOps("star").intersect("star2");
//并集
Set<String> union = stringRedisTemplate.boundSetOps("star").union("star2");
//差集
Set<String> diff = stringRedisTemplate.boundSetOps("star").diff("star2");
Set<String> diff2 = stringRedisTemplate.boundSetOps("star2").diff("star1");
5.7.10 zset类型
//添加数据
stringRedisTemplate.boundZSetOps("ranking").add("孤勇者",1);
stringRedisTemplate.boundZSetOps("ranking").add("小苹果",1.5);
stringRedisTemplate.boundZSetOps("ranking").add("神女劈观",1.2);
stringRedisTemplate.boundZSetOps("ranking").add("笨小孩",1.3);
//按分数正序排序
Set<String> r1 = stringRedisTemplate.boundZSetOps("ranking").range(0, -1);
System.out.println(r1);
//按分数倒序排序
Set<String> r2 = stringRedisTemplate.boundZSetOps("ranking").reverseRange(0, -1);
System.out.println(r2);
Set<String> r3 = stringRedisTemplate.boundZSetOps("ranking").rangeByScore(1, 1.3);
System.out.println(r3);
其余的使用方式和string的类似,如生产时间设置
5.7.11 对象数据
使用redis的string 来保存集合数据
List<Emp> empList = new ArrayList<>();
empList.add(new Emp(101, "张三", "男", 123.0));
empList.add(new Emp(102, "李四", "女", 123.0));
empList.add(new Emp(103, "王五", "女", 123.0));
empList.add(new Emp(104, "赵六", "男", 123.0));
//使用redis来缓存这个数据
// string hash ==> list 队列 set 去重 zset 排序
//String 类型 列表数据量比较小的时候就可以他
String string = om.writeValueAsString(empList);
//保存redis
stringRedisTemplate.boundValueOps("emp_list").set(string);
读取redis的string中json的数据
String emp_list = stringRedisTemplate.boundValueOps("emp_list").get();
List<Emp> empList = null;
if (emp_list != null) {
//把json字符串转为empLIst 集合
empList = om.readValue(emp_list, new TypeReference<List<Emp>>() {
});
}
System.out.println(empList);
使用redis 的 hash 来保存 集合或者单个对象的数据
List<Emp> empList = new ArrayList<>();
empList.add(new Emp(101, "张三", "男", 123.0));
empList.add(new Emp(102, "李四", "女", 123.0));
empList.add(new Emp(103, "王五", "女", 123.0));
empList.add(new Emp(104, "赵六", "男", 123.0));
for (Emp emp : empList) {
//转对象为json字符串
String empString = om.writeValueAsString(emp);
//存值
stringRedisTemplate.boundHashOps("emps").put(String.valueOf(emp.getEno()),empString);
}
获取redis的hash中保存所有的json数据
Map<Object, Object> emps = stringRedisTemplate.boundHashOps("emps").entries();
for (Map.Entry<Object, Object> en : emps.entrySet()) {
String key = (String) en.getKey();
String value = (String) en.getValue();
System.out.println(key+"=="+value+"\n");
}
获取保存在redis中的单个json数据
String emps = (String) stringRedisTemplate.boundHashOps("emps").get("101");
Emp e = om.readValue(emps,Emp.class);
System.out.println(e);