redis可以用来缓存用户登录信息,一般采用key-value方式来存储,所以可以选择redis的string,hash类型。下面采用hash来存储下用户登录信息的案例:
1.现在docker安装redis并启动:查看案例:
https://www.jianshu.com/p/a18fba0ee383
2.构建一个springboot项目:
添加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.3.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>redisdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>redisdemo</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-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.10.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
主要类:
RedisConfig:
package com.example.redisdemo.config;
import org.springframework.beans.factory.annotation.Autowired;
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.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* <p>配置</p>
*
* @author ChenXiHua
* @date 2020/5/24
*/
@Configuration
public class RedisConfig {
/**
* 注入 RedisConnectionFactory
*/
@Autowired
RedisConnectionFactory redisConnectionFactory;
/**
* 实例化 RedisTemplate 对象
*
*/
@Bean
public RedisTemplate<String, Object> createRedisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
initializeRedisTemplate(redisTemplate, redisConnectionFactory);
return redisTemplate;
}
/**
* 设置数据存入 redis 的序列化方式
*
*/
private void initializeRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory redisConnectionFactory) {
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
//序列化为Json
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setConnectionFactory(redisConnectionFactory);
}
/**
* 实例化 HashOperations 对象,可以使用 Hash 类型操作
*
*/
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
/**
* 实例化 ValueOperations 对象,可以使用 String 操作
*
*/
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 实例化 ListOperations 对象,可以使用 List 操作
*
*/
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
/**
* 实例化 SetOperations 对象,可以使用 Set 操作
*
*/
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* 实例化 ZSetOperations 对象,可以使用 ZSet 操作
*
*/
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}
RedisHashUtil:
package com.example.redisdemo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* <p>工具类</p>
*
* @author ChenXiHua
* @date 2020/5/24
*/
@Component
public class RedisHashUtil<T> {
@Autowired
protected RedisTemplate<String, Object> redisTemplate;
@Resource
protected HashOperations<String, String, T> hashOperations;
private String getRedisKey() {
return "REDIS_DEMO";
}
/**
* 添加
*
* @param key key
* @param value 对象
* @param expire 过期时间(单位:秒),传入 -1 时表示不设置过期时间
*/
public void put(String key, T value, long expire) {
hashOperations.put(getRedisKey(), key, value);
if (expire != -1) {
redisTemplate.expire(getRedisKey(), expire, TimeUnit.SECONDS);
}
}
/**
* 删除
*
* @param key 传入key的名称
*/
public void remove(String key) {
hashOperations.delete(getRedisKey(), key);
}
/**
* 查询
*
* @param key 查询的key
* @return
*/
public T get(String key) {
return hashOperations.get(getRedisKey(), key);
}
/**
* 获取当前redis库下所有value
*
* @return
*/
public List<T> getAll() {
return hashOperations.values(getRedisKey());
}
/**
* 查询查询当前redis库下所有key
*
* @return
*/
public Set<String> getKeys() {
return hashOperations.keys(getRedisKey());
}
/**
* 判断key是否存在redis中
*
* @param key 传入key的名称
* @return
*/
public boolean isKeyExists(String key) {
return hashOperations.hasKey(getRedisKey(), key);
}
/**
* 查询当前key下缓存数量
*
* @return
*/
public long count() {
return hashOperations.size(getRedisKey());
}
/**
* 清空redis
*/
public void clear() {
Set<String> set = hashOperations.keys(getRedisKey());
set.stream().forEach(key -> hashOperations.delete(getRedisKey(), key));
}
}
在test包下写个测试类:
RedisdemoApplicationTests:
package com.example.redisdemo;
import com.example.redisdemo.config.RedisHashUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
/**
* <p>测试类</p>
*
* @author ChenXiHua
* @date 2020/5/24
*/
@SpringBootTest
class RedisdemoApplicationTests {
@Autowired
RedisHashUtil<String> redisHashUtil;
@Test
public void firstRedisTest() {
System.out.println("***********************测试向Redis插入数据");
redisHashUtil.put("id","1",-1);
redisHashUtil.put("name","姓名",-1);
redisHashUtil.put("account","123",-1);
System.out.println("**********************测试从Redis读取数据,以及查询数据总数");
long count = redisHashUtil.count();
List<String> all = redisHashUtil.getAll();
System.out.println("遍历hash中的value,共计"+redisHashUtil.count()+"个。分别为:");
for (String s:all) {
System.out.print(s+" ");
}
System.out.println("");
System.out.println("***********************测试Redis中是否存在指定数据");
if(redisHashUtil.isKeyExists("one")){
String one = redisHashUtil.get("one");
System.out.println("one为:"+one);
}
System.out.println("***********************测试从Redis中删除数据");
redisHashUtil.remove("id");
if(!redisHashUtil.isKeyExists("id")){
System.out.println("id被移除了");
}
System.out.print("剩余还有:");
redisHashUtil.getKeys().forEach(key-> System.out.print(key+" "));
System.out.println("");
System.out.println("***********************测试清空Redis中的hash数据");
//redisHashUtil.clear();
System.out.println("所有都被清空,剩余:"+ redisHashUtil.count() + "个");
}
@Test
void contextLoads() {
}
}
运行测试类效果:
***********************测试向Redis插入数据
**********************测试从Redis读取数据,以及查询数据总数
遍历hash中的value,共计3个。分别为:
1 姓名 123
***********************测试Redis中是否存在指定数据
***********************测试从Redis中删除数据
id被移除了
剩余还有:name account
***********************测试清空Redis中的hash数据
所有都被清空,剩余:2个
在docker中redis使用命令查看(REDIS_DEMO是hash的key):HGETALL REDIS_DEMO
image.png
网友评论