@RunWith
(
SpringJUnit4ClassRunner
.
class
)
@ContextConfiguration
(
locations
=
{
"classpath*:/applicationContext-test.xml"
})
public class
RedisStringTest
extends
UnitilsJUnit4
{
@Autowired
private
RedisTemplate
<
String
,
Object
>
redisTemplate
;
@Resource
(
name
=
"redisTemplate"
)
private
ValueOperations
<
String
,
String
>
opsForValue
;
/**
* String
类型的
CRUD,
重复
set
为修改操作
,
以及批量添加和删除
,
查找
,
设置生存时间
,
以及
value
的增减
;
*/
@Test
public void
test
() {
String
key1
=
"test_name:"
+
1
;
opsForValue
.
set
(
key1
,
"
张三
"
)
;
String
key2
=
"test_name:"
+
2
;
opsForValue
.
set
(
key2
,
"
李四
"
)
;
String
key3
=
"test_name:"
+
3
;
opsForValue
.
set
(
key3
,
"
王五
"
)
;
String
name
=
opsForValue
.
get
(
key1
)
;
System
.
out
.
println
(
name
)
;
String
s
=
redisTemplate
.
opsForValue
()
.
get
(
"test_name:*"
,
0
,
2
)
;
ArrayList
<
String
>
strings
=
new
ArrayList
<>
()
;
strings
.
add
(
key1
)
;
strings
.
add
(
key2
)
;
List
<
Object
>
objects
=
redisTemplate
.
opsForValue
()
.
multiGet
(
strings
)
;
//
批量获取对象
;
//TimeUnit
是
timeout
的类型
,
如毫秒
\
秒
\
天等
(set
值的时候指定值的生存时间
);
redisTemplate
.
opsForValue
()
.
set
(
"test_name:"
+
6
,
"
孙七
"
,
1
,
TimeUnit
.
DAYS
)
;
Long
size
=
redisTemplate
.
opsForValue
()
.
size
(
"test_name:"
+
6
)
;
//
获取该
key
存的字符串的长度
Map
<
String
,
String
>
map
=
new
HashMap
<>
()
;
map
.
put
(
"test_name:"
+
7
,
"
刘八
"
)
;
map
.
put
(
"test_name:"
+
8
,
"
刘九
"
)
;
redisTemplate
.
opsForValue
()
.
multiSet
(
map
)
;
//
批量添加
;
String
key4
=
"test_count_id"
+
5
;
opsForValue
.
set
(
key4
,
"10"
)
;
//
常用于点赞
,
阅读数等统计
,
Long
increment
=
redisTemplate
.
opsForValue
()
.
increment
(
key4
,
1L
)
;//注意为long类型
//
给指定的
key
的
value
的值做增减
,
并返回增减后的值
Long
increment2
=
redisTemplate
.
opsForValue
()
.
increment
(
key4
, -
1L
)
;
//
给指定的
key
的
value
的值做增减
,
redisTemplate
.
opsForValue
()
.
append
(
key3
,
"
和王六
"
)
;
//
在
key
键对应值的右面追加值
value
String
s1
=
opsForValue
.
get
(
key3
)
;
//
可以看到并没有删除等方法
,
博主研究了一下可以这样
:21.del key------21.
redisTemplate
.
delete
(
key3
)
;
//
可以批量删
redisTemplate
.
delete
(
strings
)
;
//
可以批量删
Boolean
aBoolean
=
redisTemplate
.
hasKey
(
key3
)
;
Boolean
aBoolean2
=
redisTemplate
.
hasKey
(
key1
)
;
Boolean
aBoolean1
=
redisTemplate
.
hasKey
(
key2
)
;
}
}
转载请注明原文地址: https://www.6miu.com/read-26056.html