入门:
引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
yml配置文件:
spring:
redis:
database: 0
host: 139.107.71.246
port: 6379
password: # 密码(默认为空)
timeout: 6000 # 连接超时时长(毫秒)
pool:
max-active: 1000 # 连接池最大连接数(使用负值表示没有限制)
max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 10 # 连接池中的最大空闲连接
min-idle: 5 # 连接池中的最小空闲连接
加入 data redis 配置文件(不是必须的,配置序列化):
package io.sr.modules.biz.sys.conf;
import java.net.UnknownHostException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
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.core.StringRedisTemplate;
/**
* @Description: Redis配置文件
* @author 刘彦青
* @date 2018年3月1日
*/
@Configuration
public class RedisConfiguration {
@Bean
@ConditionalOnMissingBean(name="redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException{
RedisTemplate<Object, Object> template = new RedisTemplate<Object,Object>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean(StringRedisTemplate.class)
public StringRedisTemplate stringRedisTemplate(
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException{
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
使用:
RedisTemplate中定义了对5种数据结构操作
redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set
public class RedisUtils {
@Autowired
private StringRedisTemplate template;
public void setKey(String key,String value){
ValueOperations<String, String> ops = template.opsForValue();
ops.set(key,value);
}
public String getValue(String key){
ValueOperations<String, String> ops = this.template.opsForValue();
return ops.get(key);
}
常用的一些操作:
template.opsForValue().set("key", "100",60*10,TimeUnit.SECONDS);//向redis里存入数据和设置缓存时间
template.boundValueOps("key").increment(-1);//val做-1操作
template.opsForValue().get("key")//根据key获取缓存中的val
template.boundValueOps("key").increment(1);//val +1
template.getExpire("key")//根据key获取过期时间
template.getExpire("key",TimeUnit.SECONDS)//根据key获取过期时间并换算成指定单位
template.delete("key");//根据key删除缓存
template.hasKey("key");//检查key是否存在,返回boolean值
template.opsForSet().add("key", "1","2","3");//向指定key中存放set集合
template.expire("key",1000 , TimeUnit.MILLISECONDS);//设置过期时间
template.opsForSet().isMember("key", "1")//根据key查看集合中是否存在指定数据
template.opsForSet().members("key");//根据key获取set集合
template.opsForList().leftPushAll("key",new ArrayList());//存入list格式的缓存
template.opsForList().leftPush("key","value");//存入list类型的缓存中左边加入一个值的
template.opsForList().index("key", 1);//获取集合指定位置的值。
template.opsForList().range("key", 1,10);//获取某个区间的值。
如何保存一个java对象
1.在使用时设置序列化方式
@Resource
private RedisTemplate<String,Object> objectRedisTemplate;
public void test(){
objectRedisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(User.class));
User user = new User()
//存储
objectRedisTemplate.opsForValue().set("key",user);
//取值
User o = (User)objectRedisTemplate.opsForValue().get("key");
}
每次使用都要设置序列化方式效率不高,不建议使用
2.修改属性注入方式
private RedisTemplate<String,Object> redisTemplate;
@Autowired(required = false)
public void setRedisTemplate(RedisTemplate<String,Object> stringRedisTemplate) {
stringRedisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(User.class));
this. redisTemplate = redisTemplate;
}
3.构造器注入
private final RedisTemplate<String,Object> redisTemplate;
public RedisTemplateTest(RedisTemplate<String,Object> stringRedisTemplate) {
stringRedisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(User.class));
this. redisTemplate = redisTemplate;
}
常用API
Redis的String数据结构 (推荐使用StringRedisTemplate)
- set void set(K key, V value);
set void set(K key, V value, long timeout, TimeUnit unit)
- set void set(K key, V value, long offset);
该方法是用 value 参数覆写(overwrite)给定 key 所储存的字符串值,从偏移量 offset 开始
- setIfAbsent Boolean setIfAbsent(K key, V value);
- multiSet void multiSet(Map<? extends K, ? extends V> m);
为多个键分别设置它们的值
- multiSetIfAbsent Boolean multiSetIfAbsent(Map<? extends K, ? extends V> m);
为多个键分别设置它们的值,如果存在则返回false,不存在返回true
- get V get(Object key);
- getAndSet V getAndSet(K key, V value);
设置键的字符串值并返回其旧值
- multiGet List multiGet(Collection keys);
为多个键分别取出它们的值
- increment Long increment(K key, long delta);
自增 支持整数, 当key已经存在时,这个可以实现自增或自减, value值等于旧值+delta
- increment Double increment(K key, double delta);
也支持浮点数
- append Integer append(K key, String value);
如果key已经存在并且是一个字符串,则该命令将该值追加到字符串的末尾。如果键不存在,则它被创建并设置为空字符串,因此APPEND在这种特殊情况下将类似于SET。
- get String get(K key, long start, long end);
截取key所对应的value字符串
- size Long size(K key);
返回key所对应的value值得长度
- setBit Boolean setBit(K key, long offset, boolean value);
对 key 所储存的字符串值,设置或清除指定偏移量上的位(bit)
key键对应的值value对应的ascii码,在offset的位置(从左向右数)变为value
- getBit Boolean getBit(K key, long offset);
获取键对应值的ascii码的在offset处位值
set的一些操作
// 1、add(key,V... values) 向变量中批量添加值
redisTemplate.opsForSet().add("setValue","A","B","C","B","D","E","F");
//2、members(key) 获取变量中的值。
Set set = redisTemplate.opsForSet().members("setValue");
//3、size(Kkey):获取变量中值的个数。
longsetLength = redisTemplate.opsForSet().size("setValue");
//4、randomMember(Kkey):随机获取变量中的元素。
Object randomMember = redisTemplate.opsForSet().randomMember("setValue");
//5、randomMembers(Kkey, long count):随机获取变量中指定个数的元素。
List randomMembers = redisTemplate.opsForSet().randomMembers("setValue",2);
//6、isMember(Kkey,Objecto):检查给定的元素是否在变量中。
booleanisMember = redisTemplate.opsForSet().isMember("setValue","A");
//7、move(Kkey,Vvalue,KdestKey):转移变量的元素值到目的变量。
booleanisMove = redisTemplate.opsForSet().move("setValue","A","destSetValue");
if(isMove){
set = redisTemplate.opsForSet().members("setValue");
System.out.print("通过move(K key, V value, K destKey)方法转移变量的元素值到目的变量后的剩余元素:"+ set);
set = redisTemplate.opsForSet().members("destSetValue");
System.out.println(",目的变量中的元素值:"+ set);
}
8、pop(Kkey)
弹出变量中的元素。
Object popValue = redisTemplate.opsForSet().pop("setValue");
System.out.print("通过pop(K key)方法弹出变量中的元素:"+ popValue);
set = redisTemplate.opsForSet().members("setValue");
System.out.println(",剩余元素:"+ set)
9、remove(Kkey,Object... values)
批量移除变量中的元素。
longremoveCount = redisTemplate.opsForSet().remove("setValue","E","F","G");
System.out.print("通过remove(K key, Object... values)方法移除变量中的元素个数:"+ removeCount);
set = redisTemplate.opsForSet().members("setValue");
System.out.println(",剩余元素:"+ set);
10、scan(Kkey,ScanOptionsoptions)
匹配获取键值对,ScanOptions.NONE为获取全部键值对;ScanOptions.scanOptions().match("C").build()匹配获取键位map1的键值对,不能模糊匹配。
//Cursor<Object> cursor = redisTemplate.opsForSet().scan("setValue", ScanOptions.NONE);
Cursor cursor = redisTemplate.opsForSet().scan("setValue", ScanOptions.scanOptions().match("C").build());
while(cursor.hasNext()){
Object object = cursor.next();
System.out.println("通过scan(K key, ScanOptions options)方法获取匹配的值:"+ object);
}
11、difference(Kkey,Collection<K> otherKeys)
通过集合求差值。
List list =newArrayList();
list.add("destSetValue");
Set differenceSet = redisTemplate.opsForSet().difference("setValue",list);
System.out.println("通过difference(K key, Collection<K> otherKeys)方法获取变量中与给定集合中变量不一样的值:"+ differenceSet);
12、difference(Kkey,KotherKey)
通过给定的key求2个set变量的差值。
differenceSet = redisTemplate.opsForSet().difference("setValue","destSetValue");
System.out.println("通过difference(K key, Collection<K> otherKeys)方法获取变量中与给定变量不一样的值:"+ differenceSet);
13、differenceAndStore(Kkey,KotherKey,KdestKey)
将求出来的差值元素保存。
redisTemplate.opsForSet().differenceAndStore("setValue","destSetValue","storeSetValue");
set = redisTemplate.opsForSet().members("storeSetValue");
System.out.println("通过differenceAndStore(K key, K otherKey, K destKey)方法将求出来的差值元素保存:"+ set);
14、differenceAndStore(Kkey,Collection<K> otherKeys,KdestKey)
将求出来的差值元素保存。
redisTemplate.opsForSet().differenceAndStore("setValue",list,"storeSetValue");
set = redisTemplate.opsForSet().members("storeSetValue");
System.out.println("通过differenceAndStore(K key, Collection<K> otherKeys, K destKey)方法将求出来的差值元素保存:"+ set);
15、distinctRandomMembers(Kkey, long count)
获取去重的随机元素。
set = redisTemplate.opsForSet().distinctRandomMembers("setValue",2);
System.out.println("通过distinctRandomMembers(K key, long count)方法获取去重的随机元素:"+ set);
16、intersect(Kkey,KotherKey)
获取2个变量中的交集。
set = redisTemplate.opsForSet().intersect("setValue","destSetValue");
System.out.println("通过intersect(K key, K otherKey)方法获取交集元素:"+ set);
17、intersect(Kkey,Collection<K> otherKeys)
获取多个变量之间的交集。
set = redisTemplate.opsForSet().intersect("setValue",list);
System.out.println("通过intersect(K key, Collection<K> otherKeys)方法获取交集元素:"+ set);
18、intersectAndStore(Kkey,KotherKey,KdestKey)
获取2个变量交集后保存到最后一个参数上。
redisTemplate.opsForSet().intersectAndStore("setValue","destSetValue","intersectValue");
set = redisTemplate.opsForSet().members("intersectValue");
System.out.println("通过intersectAndStore(K key, K otherKey, K destKey)方法将求出来的交集元素保存:"+ set);
19、intersectAndStore(Kkey,Collection<K> otherKeys,KdestKey)
获取多个变量的交集并保存到最后一个参数上。
redisTemplate.opsForSet().intersectAndStore("setValue",list,"intersectListValue");
set = redisTemplate.opsForSet().members("intersectListValue");
System.out.println("通过intersectAndStore(K key, Collection<K> otherKeys, K destKey)方法将求出来的交集元素保存:"+ set);
20、union(Kkey,KotherKey)
获取2个变量的合集。
set = redisTemplate.opsForSet().union("setValue","destSetValue");
System.out.println("通过union(K key, K otherKey)方法获取2个变量的合集元素:"+ set);
21、union(Kkey,Collection<K> otherKeys)
获取多个变量的合集。
set = redisTemplate.opsForSet().union("setValue",list);
System.out.println("通过union(K key, Collection<K> otherKeys)方法获取多个变量的合集元素:"+ set);
22、unionAndStore(Kkey,KotherKey,KdestKey)
获取2个变量合集后保存到最后一个参数上。
redisTemplate.opsForSet().unionAndStore("setValue","destSetValue","unionValue");
set = redisTemplate.opsForSet().members("unionValue");
System.out.println("通过unionAndStore(K key, K otherKey, K destKey)方法将求出来的交集元素保存:"+ set);
23、unionAndStore(Kkey,Collection<K> otherKeys,KdestKey)
获取多个变量的合集并保存到最后一个参数上。
redisTemplate.opsForSet().unionAndStore("setValue",list,"unionListValue");
set = redisTemplate.opsForSet().members("unionListValue");
System.out.println("通过unionAndStore(K key, Collection<K> otherKeys, K destKey)方法将求出来的交集元素保存:"+ set);
redis 发布与订阅 : https://zhuanlan.zhihu.com/p/20948779
详细用法:https://www.jianshu.com/p/7bf5dc61ca06