Table of contents
Redis Visualization Tool_Install Redis_Desktop_Manager
Download Redis Desktop Manager
Java integrated Redis_Jedis operation
Java integration Redis_Spring-Data-Redis
RedisTemplate defines five data structure operations
StringRedisTemplate与RedisTemplate
Configure in application.properties
Use redisTemplate for various types of CURD operations
Redis data type_Bitmaps
Introduction
In computers, binary (bit) is used as the basic unit for storing information, and 1 byte is equal to 8 bits. For example, the "abc" string is composed of 3 bytes, and its binary representation is used for computer storage. The ASCII codes corresponding to "abc" are 97, 98, and 99, and the corresponding binary codes are 01100001, 01100010, and 01100011, which are stored in memory Expressed as follows:
Reasonable use of bits can effectively improve memory usage and development efficiency.
Redis provides the "data structure" of Bitmaps, which can realize bit operations:
Common commands
setbit
Set the value of an offset in Bitmaps.
Grammatical structures:
setbit key offset value
Example:
Bitmaps in redis can be used to count user information, eg: active days, check-in days, and login days bitmaps bitmaps are all binary operations for recording, and there are only two states of 0 and 1
127.0.0.1:6379> getbit sign 1 # 获取第一天的打卡状态 (integer) 1 127.0.0.1:6379> BITCOUNT sign # 统计所有打卡天数 (integer) 4127.0.0.1:6379> setbit zhangsan:3 1 1 # 往sign中添加数据,第1天打卡 (integer) 1 127.0.0.1:6379> setbit zhangsan:3 2 0 # 第2天未打卡 (integer) 0 127.0.0.1:6379> setbit zhangsan:3 3 1 # 第3天打卡 (integer) 0 127.0.0.1:6379> setbit zhangsan:3 4 0 # 第4天未打卡 (integer) 0 127.0.0.1:6379> setbit zhangsan:3 5 1 # 第5天打卡 (integer) 0 127.0.0.1:6379> setbit zhangsan:3 6 0 # 第6天未打卡 (integer) 0 127.0.0.1:6379> setbit zhangsan:3 7 1 # 第7天打卡 (integer) 0 127.0.0.1:6379> getbit sign 1 # 获取第一天的打卡状态 (integer) 1 127.0.0.1:6379> BITCOUNT sign # 统计所有打卡天数 (integer) 4 127.0.0.1:6379> getbit sign 1 # 获取第一天的打卡状态 (integer) 1
getbit
Get the value of an offset in Bitmaps.
Grammatical structures:
getbit key offset
Example: Get the offset value of the key.
getbit sign 3 获取偏移量为1的值,结果为1
Also returns 0 if offset does not have a value set.
getbit sign 99 获取偏移量为99的值,结果为0
bitcount
Counts the number of bits in the string that are set to 1. Under normal circumstances, the entire given string will be counted. You can choose to use additional start and end parameters to specify the range of byte groups for statistics (including start and end). 0 means the first element, -1 means the last element.
Grammatical structures:
bitcount key [start end]
Example:
bitcount sign 获取整个字符串被设置为1的bit数量,结果为3
For example: currently there is a bitmaps with key k1 storing [00000001, 00000001, 00000010, 00000011], which correspond to [1, 1, 2, 3] respectively.
setbit num 7 1 setbit num 15 1 setbit num 22 1 setbit num 30 1 setbit num 31 1 bitcount num 1 2 统计索引1、2两个字节组中bit=1的数量,即统计00000001,00000010中bit=1的数 量,结果为2 bitcount num 1 3 统计索引1、2、3三个字节组中bit=1的数量,即统计 00000001,00000010,00000011中bit=1的数量,结果为4 bitcount num 0 -1 统计所有的字节组中bit=1的数量,结果为5
What setbit sets or gets is the bit (bit) position, and bitcount calculates the byte (byte) position.
bitop
Merge multiple bitmaps into a new bitmap by intersection/union.
Grammatical structures:
bitop and/or destkey sourcekey1 sourcekey2……
Example:
bitop and k3 k1 k2 通过求交集将k1 k2合并成k3 bitop or k3 k1 k2 通过求并集将k1 k2合并成k3
real-time learning feedback
1. How to set the value of an offset in Bitmaps in the Redis technology Bitmaps data type.
A setbit
B getbit
C bitcount
D bitop
2. How to obtain the value of a certain offset in Bitmaps in the Redis technology Bitmaps data type.
A setbit
B getbit
C bitcount
D bitop
Redis data type_Geospatia
Introduction
GEO, Geographic, the abbreviation of geographic information. This type is the two-dimensional coordinates of the element, which is the latitude and longitude on the map. Based on this type, Redis provides common operations such as longitude and latitude setting, query, range query, distance query, and longitude and latitude Hash.
Common commands
geoadd
It is used to store the specified geospatial location, and one or more longitude (longitude), latitude (latitude), and location name (member) can be added to the specified key.
Grammatical structures:
geoadd key longitude latitude member
Example:
# 将北京的经纬度和名称添加到china geoadd china 116.405285 39.904989 beijing # 将成都和上海的经纬度、名称添加到china geoadd china 104.065735 30.659462 chengdu 121.472644 31.231706 shanghai
geopos
Returns all locations (longitude and latitude) of the specified name (member) from the given key, or nil if none exists.
Grammatical structures:
geopos key member [member ……]
Example: Return the latitude and longitude of shanghai and beijing in China
geopos chinacity shanghai beijing
geodist
Used to return the distance between two given locations.
Grammatical structures:
geodist key member1 member2 [m|km|ft|mi]
Example:
# 返回shanghai和beijing之间的距离,结果1067597.9668,单位米 geodist chinacity shanghai beijing # 返回shanghai和chengdu之间的距离,结果1660.0198,单位是千米 geodist chinacity shanghai chengdu km
georadius
With the given longitude latitude (longitude latitude) as the center, returns all location elements contained in the key whose distance from the center does not exceed the given maximum distance (radius).
Grammatical structures:
georadius key longitude latitude radius m|km|ft|mi
Example:
#获取经纬度110 30为中心,在china内1200公里范围内的所有元素。 georadius china 110 30 1200 km
real-time learning feedback
1. How to store the specified geospatial location in the Geospatia data type of Redis technology.
A geoadd
B geopos
C geodist
D georadius
2. How to calculate the distance between two given locations in the Redis technology Geospatia data type.
A geoadd
B geopos
C geodist
D georadius
Redis data type_Hyperloglog
Introduction
When we do site traffic statistics, we usually count page UV (unique visitor: unique visitor) and PV (ie page views: page view). Redis HyperLogLog is an algorithm for cardinality statistics. The advantage of HyperLogLog is that when the number or volume of input elements is very, very large, the space required to calculate the cardinality is always fixed and small.
what is base
For example, the data set {1,3,5,7,5,7,8}, then the cardinality set of this data set is {1,3,5,7,8}, and the cardinality (non-repeating elements) is 5. Cardinality estimation It is to quickly calculate the base within the acceptable range of error.
Common commands
pathd
Add all element parameters to the Hyperloglog data structure.
Grammatical structures:
pfadd key element1 element2……
Example:
Returns 1 if at least one element was added, 0 otherwise.
pfadd book1 uid1 uid2 uid
Notice:
Add elements to HyperLogLog, return 1 if there is a change inside, and return 0 if there is no change.
pfcount
Calculate the approximate cardinality of Hyperloglog, you can calculate multiple Hyperloglogs, and count the total cardinality.
Grammatical structures:
pfcount key1 key2……
Example:
pfcount book1 #计算book1的基数,结果为3 pfadd book2 uid3 uid4 #添加两个元素到book2中 pfcount book1 book2 #统计两个key的基数总数,结果为5
pfmerge
Merge one or more Hyperloglogs (sourcekey1) into one Hyperloglog (destkey).
Grammatical structures:
pfmerge destkey sourcekey1 sourcekey2……
Example: For example, monthly active users can be calculated by combining daily active users.
#将book1和book2合并成book,结果为5 pfmerge book book1 book2
scenes to be used
The cardinality is not large, and the amount of data is not large, so it will not be used. It will be a bit overkill and waste space. It has limitations, that is, it can only count the number of cardinal numbers, but there is no way to know what the specific content is. Compared with bitmap, it belongs to two specific types. Statistically speaking, HyperLogLog deduplication is much more convenient than bitmaps. Generally, bitmap and hyperloglog can be used together, and bitmap identifies which users are active.
real-time learning feedback
1. Redis HyperLogLog is an algorithm used to do ____.
A statistical calculation
Class B
C aggregate statistics
D statistical base
Redis Visualization Tool_Install Redis_Desktop_Manager
Download Redis Desktop Manager
Note: Official website https://rdm.dev/pricing
Choose the installation path
Connect to Redis service
turn off firewall
systemctl stop firewalld.service
Disable protected mode
protected-mode no
Enable remote access
By default, redis only allows local access. To enable redis to be accessed remotely, redis.conf can be modified.
注释掉bind 127.0.0.1 可以使所有的ip访问redis
Configure connection service
configuration information
Java integrated Redis_Jedis operation
What is Jedis
Jedis is the Java connection development tool officially recommended by Redis.
Introducing Jedis
Create a maven project
Introduce maven dependency
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
Jedis connects to redis
//第一个参数是ip地址,第二个参数是端口
Jedis jedis = new Jedis("192.168.56.31",6379);
Test related data types
Connect to Redis service
Jedis jedis = new Jedis("192.168.56.31",6379);
//通过ping()方法向redis发送一个ping命令,服务器返回一个Pong
String msg = jedis.ping();
System.out.println(msg);
//jedis使用完毕需要关闭
jedis.close();
Jedis-API:String
//设置一个key
jedis.set("k1","v1");
//设置一个key
jedis.set("k2","1");
//获取一个key
String res = jedis.get("k1");
//对某一个key自增
Long ires = jedis.incr("k2");
Jedis-API:Keys
//返回所有的key
Set<String> keys = jedis.keys("*");
//返回该key剩余过期时间
Long time = jedis.ttl("k1");
Jedis-API:List
//向list中添加数据
jedis.lpush("list1","v1","v2","v3");
//返回list全部数据
List<String> list = jedis.lrange("list1",0,-1 );
Jedis-API:Set
//向set中添加数据
jedis.sadd("set1" ,"v1","v2","v2","v3");
//查看该集合中有多少个元素
jedis.smembers("set1");
Jedis-API:Hash
//设置一个hash
jedis.hset("user","age","25");
//获取该key的所有value
jedis.hvals("user");
Jedis-API:Zset
//向zset中添加一条数据
jedis.zadd("zset1",100,"java");
//获取所有的值
jedis.zrange("zset1",0,-1);
Jedis-API:Bitmaps
//将b1偏移量为0的位设置为1
jedis.setbit("b1",0, "1");
//获取b1偏移量为0的位
jedis.getbit("b1",0);
Jedis-API:Geospatia
//添加一条地理信息数据
jedis.geoadd("chinacity",130,110,"xiaotong");
Jedis-API:Hyperloglog
//将所有元素参数添加到 Hyperloglog 数据结构中。
jedis.pfadd("book","c++","java","php");
Java integration Redis_Spring-Data-Redis
Introduction
Spring-Data-Redis is a part of the spring family. It accesses the Redis service through simple configuration, and highly encapsulates the underlying development kits of Reids (Jedis, JRedis, and RJC). RedisTemplate provides various operations, exception handling and sequences of Redis. , support publish and subscribe.
Introduction to RedisTemplate
Spring encapsulates the RedisTemplate object to perform various operations on Redis, and it supports all Redis native APIs.
org.springframework.data.redis.core
Class RedisTemplate<K,V>
RedisTemplate defines five data structure operations
redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set
StringRedisTemplate与RedisTemplate
pom.xml add dependencies
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Configure in application.properties
#Redis服务器连接地址
spring.redis.host=192.168.56.31
#Redis服务器连接端口
spring.redis.port=6379
#连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
#连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
#连接池中的最大空闲连接
spring.redis.pool.max-idle=8
#连接池中的最小空闲连接
spring.redis.pool.min-idle=0
#连接超时时间(毫秒)
spring.redis.timeout=30000
custom serialization
/**
* 自定义序列化方式
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
}
Use redisTemplate for various types of CURD operations
String data type operations
add element
public boolean set(String key,Object value){
try{
redisTemplate.opsForValue().set(key,value);
return true;
}catch (Exception e){
log.error("redis set value exception:{}",e);
return false;
}
}
get element
public Object get(String key){
return key == null ? null : redisTemplate.opsForValue().get(key);
}
Add element and set expiration time
public boolean setex(String key,Object value,long expire){
try{
//TimeUnit.SECONDS指定类型为秒
redisTemplate.opsForValue().set(key,value,expire,TimeUnit.SECONDS);
return true;
}catch (Exception e){
log.error("redis set value and expire exception:{}",e);
return false;
}
}
Hash type operations
add element
public boolean hset(String key, String field, Object value,long seconds) {
try {
redisTemplate.opsForHash().put(key, field, value);
expire(key,seconds);//调用通用方法设置过期时间
return true;
}catch (Exception e){
log.error("redis hset and expire eror,key:{},field:{},value: {},exception:{}",key,field,value,e);
return false;
}
}
retrieve data
public Object hget(String key,String field){
return redisTemplate.opsForHash().get(key,field);
}
set type operations
add element
public long sset(String key ,Object...values){
try {
return redisTemplate.opsForSet().add(key,values);
}catch (Exception e){
log.error("redis sset error,key:{},value:{},values:{},exception:
{}",key,values,e);
return 0;
}
}
Get the length of the set
public long sgetSize(String key){
try {
return redisTemplate.opsForSet().size(key);
}catch (Exception e){
log.error("redis sgetSize error,key:{},exception:{}",key,e);
return 0;
}
}
get element
public Set<Object> sgetAll(String key){
try {
return redisTemplate.opsForSet().members(key);
}catch (Exception e){
log.error("redis sgetAll error,key:{},exception:{}",key,e);
return null;
}
}
Operations of type zset
add element
public boolean zadd(String key,Object member,double score){
try {
return redisTemplate.opsForZSet().add(key,member,score);
} catch (Exception e) {
log.error("redis zadd error,key:{},value:{},score:{},exception:
{}",key,member,score,e);
return false;
}
}
get element
public Set<String> zrange(String key,int start,int end){
try {
Set<Object> range = redisTemplate.opsForZSet().range(key, start, end);
if(range==null||range.size()==0) return null;
return range.stream().
map(o->(String)o).collect(Collectors.toSet());
} catch (Exception e) {
log.error("redis zrange error,key:{},start:{},end:{},exception:{}",key,start,end,e);
return null;
}
}
List type operations
add element
public boolean lrpush(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
log.error("redis lrpush error,key:{},value:{}exception:
{}",key,value,e);
return false;
}
}
get element
public List<Object> getList(String key,int start,int end) {
try {
List<Object> o = redisTemplate.opsForList().range(key,start,end);
return o;
} catch (Exception e) {
return null;
}
}