Spring-boot通过redisTemplate使用redis(无须手动序列化)-3
- UID
- 1066743
|
Spring-boot通过redisTemplate使用redis(无须手动序列化)-3
#开始使用
package com.biologic.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import com.biologic.entity.User;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisApplicationTests {
@Autowired
private RedisTemplate<Object, Object> template;
@Test
public void contextLoads() {
User user = new User();
user.setId("1");
user.setName("joe");
user.setPassword("123");
template.opsForValue().set(user.getId()+"",user);
//原本opsForValue()是只能操作字符串的.现在就可以操作对象了
User result = (User) template.opsForValue().get(user.getId()+"");
System.out.println(result.getId()+" "+result.getName());
}
}
输出结果:
1 joe
1
RedisTemplate中定义了对5种数据结构操作
redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set
使用:String[] strarrays = new String[]{"strarr1","sgtarr2"};
System.out.println(template.opsForSet().add("setTest", strarrays));
结果:2
使用:System.out.println(template.opsForSet().size("setTest"));
结果:1 |
|
|
|
|
|