Redis简介
基于内存进行存储, 支持key-value的存储形式, 底层是c语言编写
基于key-value形式的数据字典, 结构非常简单, 没有数据表的概念,直接用键值对的形式完成数据的管理,Redis支持五种数据类型:
- 字符串
- 列表
- 集合
- 有序集合
- 哈希
启动Redis服务
windows, 打开cmd进入redids的目录输入: redis-server.exe
启动好redis服务后打开一个新的cmd输入: redis-cli.exe
linux没操作过
sudo ./bin/redis-server ./etc/redis.conf
./bin/redis-cli
出现127.0.0.1:6379代表服务已经启动好了
Spring Boot 整合Redis之CRUD
Spring Data Redis 操作redis
1 .引入Redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.创建持久化类(实体类)要进行序列化接口, 否从会出现错误
public class (类名) implements Serializable{}
3.在application.yml配置Redis的连接参数
spring:
#redis的配置
redis:
database: 0
host: 主机IP
port: 6379
password: 密码
4.测试连接Redis是否成功
import org.springframework.data.redis.core.RedisTemplate;
//注入Redis
@Autowired
private RedisTemplate redisTemplate;
@RequestMapping("findById")
public Users findByIdUsers( Integer userId) {
Users users = this.usersService.selectByUserId(1);
redisTemplate.opsForValue().set("a", users);
return this.usersService.selectByUserId(userId);
}
Redis中的数据,这是阿里云的redis,下面出现了数据,表明我们向redis存入数据成功,代表redis连接成功
类型 | 键名 |
---|---|
none | ��ta |
现在进行对redis取值的操作, 打开浏览去输入:
//向redis数据库中取值, 取值时会自动将数据反序列化
@GetMapping("get/{key}")
public Users get(@PathVariable("key") String key){
return (Users)redisTemplate.opsForValue().get(key);
}
localhost:你的端口/get/a回车后,浏览器会出现数据
删除Redis中的数据
@RequestMapping("/delete/{key}")
public boolean delete(@PathVariable("key") String key){
redisTemplate.delete(key);
//haskey判断key值是否存在,falsh表示不存在,true表示存在
return redisTemplate.hasKey(key);
}
所以前端返回falsh表示已经删除成功,然后去redis中查询发现值被删除
Spring Boo操作Redis的五种数据类型
- String字符的操作
//存字符串,取字符串
@RequestMapping("/String")
public String stringTest(){
redisTemplate.opsForValue().set("str", "HelloWorld");
String str = (String)redisTemplate.opsForValue().get("str");
return str;
}
- List 列表的操作
@RequestMapping("list")
public List<String> listUser(){
ListOperations<String,String> listOperations = redisTemplate.opsForList();
listOperations.leftPush("list", "Hello");
listOperations.leftPush("list", "World");
listOperations.leftPush("list","springboot");
//从redis中取出数据
List<String> list = listOperations.range("list", 0, 2);
return list;
}
- Set集合的操作,顺序与添加数据不同
@RequestMapping("/set")
public Set<String> setText(){
SetOperations<String,String> setOperations = redisTemplate.opsForSet();
setOperations.add("set", "Hello");
setOperations.add("set", "world");
setOperations.add("set","springboot");
setOperations.add("set","springboot");
Set<String> set = setOperations.members("set");
return set;
}
- Zset 有序集合的操作, 可以控制数据的顺序
@RequestMapping("/zset")
public Set<String> zsetText(){
ZSetOperations<String,String> zSetOperations = redisTemplate.opsForZSet();
zSetOperations.add("zset", "Hello", 1);
zSetOperations.add("zset", "World", 2);
zSetOperations.add("zset", "SpringBoot", 3);
Set<String> zset = zSetOperations.range("zset", 0, 2);
return zset;
}
- Hash 哈希的操作
HashMap key value
HashOperations key hashKey value
key 是每一组数据的Id ,HashKey和Value是一组完整的HashMap数据,通过Key来区分不同的HashMap
HashMap hashMap = new HashMap();
hashMap.put(key1, value1);
HashMap hashMap = new HashMap();
hashMap.put(key2, value2);
HashMap hashMap = new HashMap();
hashMap.put(key2, value2);
HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
hashOperations.put(hashMap, key1, value1);
hashOperations.put(hashMap, key2, value2);
hashOperations.put(hashMap, key3, value3);
@RequestMapping("hash")
public void hashTest(){
HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
hashOperations.put("key", "hashKey", "hello");
System.out.println(hashOperations.get("key", "hashKey"));
}
整合Redis缓存进阶
新键一个类用于redistemplate序列化
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){
//设置缓存过期时间
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(60*30));
return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String, Object> template = new RedisTemplate<>();
//创建连接工厂
template.setConnectionFactory(factory);
//使用Jackson来序列化和序列化RedisValue值(默认使用JDK的序列化)
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
//指定要序列化的域, field,get和set,以及修饰范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//指定序列化的类型,类必须是非final修饰的,final修饰的类,比如String,Intger等会抛出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
// 值采用json序列化
template.setValueSerializer(jacksonSeial);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();
return template;
}
}
然后建一个专门操作redis的工具类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.concurrent.TimeUnit;
@Configuration
public class RedisCru {
//注入对redis数据库的操作类
@Autowired
private RedisTemplate redisTemplate;
//向redis中添加数据,并设置过期时间,时间已过自动删除
public void addRedisData(String Key, Object addData){
redisTemplate.opsForValue().set(Key, addData, 60*4, TimeUnit.SECONDS);
}
//判断redis中是否存在该数据
public boolean judgekey(String Key){
return this.redisTemplate.hasKey(Key);
}
//从redis中取出Key
public Object getRedisObject(String Key){
return (Object)redisTemplate.opsForValue().get(Key);
}
}
在控制层(Controller) 中写个方法
//注入redis操做
@Autowired
private RedisCru redisCru;
@RequestMapping("whereGoods")
public List<Goods> whereGoodsAll(){
boolean hasKey = this.redisCru.judgekey("goods");
if(!hasKey){
this.redisCru.addRedisData("goods", this.goodsService.whereGoodsAll());
System.out.println("mysql");
}
return (List<Goods>)this.redisCru.getRedisObject("goods");
}