Redis学习(三 )
1.SpringBoot整合Redis
Spring Boot Data(数据) Redis 中提供了RedisTemplate和StringRedisTemplate,其中StringRedisTemplate是RedisTemplate的子类,两个方法基本一致,不同之处主要体现在操作的数据类型不同,RedisTemplate中的两个泛型都是Object,意味着存储的key和value都可以是一个对象,而StringRedisTemplate的两个泛型都是String,意味着StringRedisTemplate的key和value都只能是字符串。
注意: 使用RedisTemplate默认是将对象序列化到Redis中,所以放入的对象必须实现对象序列化接口
1.1 环境准备
1.引入依赖 (spring2.0以后不适用jedis了,使用lettuce)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.配置application.propertie
spring.redis.host=192.168.40.110
spring.redis.port=7000
spring.redis.database=0
1.2 使用StringRedisTemplate和RedisTemplate
2.连接池
2.1引入依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
标准化的结构
主要代码:
InnerRedisController
package com.shujia.controller;
import com.shujia.eneity.MyTypeTuple;
import com.shujia.eneity.User;
import com.sun.javafx.collections.MappingChange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.Duration;
import java.util.*;
/**
* @author WangTao
* @date 2022/5/15 18:20
*/
/*
StringRedisController:操作的key是String,Value也是String的数据类型
Redis中的value的类型:string list set zset hash
RedisTemplateL: key -- object value -- object
key value
原本:String String
name --> nameXXX
现在读的时候,会将键进行序列化,将序列化后的值在取redis去找这个键,
由于原本的name是字符串且没有进行序列化。所以找不到就为空了。
RedisTemplate 默认是做JdkSerializationSerializer
如果查找的是一个字符串将序列化方式变成StringRedisSerializer序列化即可
*/
@RestController
public class InnerRedisController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate<Object,Object> redisTemplate;
//测试 RedisTemplate 读取数据
@RequestMapping("rtTest")
public String rtTest() {
//解决序列化的办法:如下
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.opsForValue().set("name","阿涛没死!");
Object name = redisTemplate.opsForValue().get("name");
System.out.println(name);
//存储一个学生对象到redis中去。
User user = new User("1001", "小王八", 19);
redisTemplate.opsForValue().set("user1", user);
return "测试 RedisTemplate 成功!";
}
@RequestMapping("testHash")
public String testHash(){
//添加一个 hash 元素
stringRedisTemplate.opsForHash().put("1001", "name", "atao");
//添加多个 hash 数据
HashMap<String,String> map = new HashMap<>();
map.put("name","向阳花");
map.put("sex","女");
map.put("age", "19");
map.put("address","灿烂的阳光下!");
stringRedisTemplate.opsForHash().putAll("hash1",map);
//取需要获取值的对应的小 key 组成一个 Collection 集合
ArrayList<Object> arrayList = new ArrayList<>();
arrayList.add("name");
arrayList.add("sex");
arrayList.add("address");
List<Object> hash1 = stringRedisTemplate.opsForHash().multiGet("hash1", arrayList);
System.out.println(hash1);
return "测试 Hash 成功!!!";
}
@RequestMapping("testZSet")
public String testZSet(){
//添加一个元素并给上分数
stringRedisTemplate.opsForZSet().add("zset1", "阿涛", 100);
//一次性添加多个元素并给上分数
//创建一个 set 集合
HashSet<ZSetOperations.TypedTuple<String>> set = new HashSet<>();
MyTypeTuple wangtao = new MyTypeTuple("阿涛", 200.0);
MyTypeTuple abing = new MyTypeTuple("abing", 50.0);
MyTypeTuple ayang = new MyTypeTuple("ayang", 20.0);
set.add(wangtao);
set.add(abing);
set.add(ayang);
stringRedisTemplate.opsForZSet().add("zset8",set);
Set<String> zset8 = stringRedisTemplate.opsForZSet().rangeByScore("zset8", 30, 280);
//查询并查看分数
Set<ZSetOperations.TypedTuple<String>> zset81 = stringRedisTemplate.opsForZSet().rangeByScoreWithScores("zset8", 10, 700);
Set<String> zset82 = stringRedisTemplate.opsForZSet().reverseRange("zset8", 0, -1);
Set<ZSetOperations.TypedTuple<String>> zset83 = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores("zset8", 0, 300);
String value = null;
for (ZSetOperations.TypedTuple<String> stringTypedTuple : zset83) {
value = stringTypedTuple.getValue();
Double score = stringTypedTuple.getScore();
System.out.println("姓名:"+value+"\n"+"成绩:"+score);
}
return "测试 zSet 集合成功!!!"+zset8+zset81+zset82+zset83+value;
}
@RequestMapping("testSet")
public String testSet(){
//一次性设置多个值;
stringRedisTemplate.opsForSet().add("set9","hadoop","java","linux","java","hive","hadoop");
//获取set 所有的值;
Set<String> set9 = stringRedisTemplate.opsForSet().members("set9");
return "测试testMap集合成功!"+set9;
}
//测试对 list 集合的操作
@RequestMapping("testList")
public String testList(){
stringRedisTemplate.opsForList().leftPush("list9","无聊就来拍抖音,");
stringRedisTemplate.opsForList().leftPush("list9","没有人看不丢人。");
stringRedisTemplate.opsForList().leftPush("list9","无聊就来拍抖音,","预备,唱 ");
List<String> list9 = stringRedisTemplate.opsForList().range("list9", 0, -1);
stringRedisTemplate.opsForList().set("list9", 1, "贵州哪有真情在,");
List<String> list0 = stringRedisTemplate.opsForList().range("list9", 0, -1);
stringRedisTemplate.opsForList().trim("list1",2, -3);
List<String> list8 = stringRedisTemplate.opsForList().range("list1", 0, -1);
return "测试 list 操作完毕!!!"+list0+list8;
}
//测试对String类型的操作
@RequestMapping("testString")
private String testString(){
//opsForValue意味着操作String类型的数据
stringRedisTemplate.opsForValue().set("name","aTao");
stringRedisTemplate.opsForValue().set("name","xiaoXiao",10L);
stringRedisTemplate.opsForValue().set("name3","haoPa", Duration.ofSeconds(19L));
stringRedisTemplate.opsForValue().set("age1","laLa",Duration.ofMinutes(10L));
String s = stringRedisTemplate.opsForValue().get("sing");
System.out.println(s);
//在原有的值上进行添加
stringRedisTemplate.opsForValue().append("sing","-再也没有留恋的斜阳,在也没有倒印的月亮");
//根据多个键获取多个值,意味着将多个键组合成 list 集合
ArrayList<String> strings = new ArrayList<>();
strings.add("b1");
strings.add("c1");
strings.add("k1");
List<String> strings1 = stringRedisTemplate.opsForValue().multiGet(strings);
System.out.println(strings1);
//一次设置多个 key value
HashMap<String, String> map = new HashMap<String, String>();
map.put("痛仰乐队","再见萨菲娜");
map.put("二手玫瑰","仙儿");
map.put("许巍","曾梦想仗剑走天涯");
stringRedisTemplate.opsForValue().multiSet(map);
System.out.println("多条数据插入成功!!!");
//将 m1 增加一;
Long m1 = stringRedisTemplate.opsForValue().increment("m1");
return "测试String连接成功!!"+s+strings1+m1;
}
//对key类型的操作
@RequestMapping("testKey")
public String testKey(){
//删除数据库中的key
Boolean name = stringRedisTemplate.delete("name");
System.out.println("删除name:"+name);
//将key转移到数据库
Boolean a1 = stringRedisTemplate.move("a1", 1);
System.out.println("移动a1:"+a1);
//遍历数据库
Set<String> keys = stringRedisTemplate.keys("*");
System.out.println("所有的键:"+keys);
System.out.println("==================================");
DataType age = stringRedisTemplate.type("age");
System.out.println("age的类型为"+age);
//判断key是否存在
Boolean address = stringRedisTemplate.hasKey("address");
System.out.println("address是否存在:"+address);
return "测试key的操作完毕!"+name;
}
}
User
package com.shujia.eneity;
import java.io.Serializable;
/**
* @author WangTao
* @date 2022/5/15 22:28
*/
public class User implements Serializable {
private static final long serialVersionUID = 4395863899415195843L;
private String id;
private String name;
private Integer age;
public User(String id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
MyTypeTuple
package com.shujia.eneity;
import org.springframework.data.redis.core.ZSetOperations;
/**
* @author WangTao
* @date 2022/5/15 20:45
*/
public class MyTypeTuple implements ZSetOperations.TypedTuple {
private String value;
private Double score;
public MyTypeTuple(String value, Double score) {
this.value = value;
this.score = score;
}
@Override
public Object getValue() {
return value;
}
@Override
public Double getScore() {
return score;
}
@Override
public int compareTo(Object o) {
return 0;
}
}
配置文件
server:
port: 9999
spring:
redis:
port: 7000
host: 192.168.44.110
database: 0 #选择使用的库
pom.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.shujia</groupId>
<artifactId>soringboot-redis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>soringboot-redis</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-maven-plugin -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>