一、添加Redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二、application.properties
# 应用名称
spring.application.name=springboot_redis
server.port=8085
#配置Redis,redis的host是虚拟机服务器上的IP地址,端口6379
spring.redis.host=127.0.0.1
spring.redis.port=6379
三、添加配置类
package com.ljx.springboot_redis.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
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.*;
import java.time.Duration;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
private static final StringRedisSerializer STRING_SERIALIZER = new StringRedisSerializer();
private static final GenericJackson2JsonRedisSerializer JACKSON__SERIALIZER = new GenericJackson2JsonRedisSerializer();
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheCfg=RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(STRING_SERIALIZER))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(JACKSON__SERIALIZER));
return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheCfg)
.build();
}
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(JACKSON__SERIALIZER);
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
四、测试
TestRedisString
package com.ljx.springboot_redis;
import org.junit.jupiter.api.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.SpringJUnit4ClassRunner;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
class TestRedisString {
@Autowired
private RedisTemplate<String,String> redisTemplate;
@Test
public void testSet(){
redisTemplate.opsForValue().set("name","heima");
redisTemplate.opsForValue().set("name1","heima1",10, TimeUnit.SECONDS);
redisTemplate.opsForValue().set("name","XX",2);
redisTemplate.opsForValue().setIfAbsent("name","heima");
Map<String,String> map = new HashMap<>();
map.put("name2","heima2");
map.put("name3","heima3");
map.put("name3","heima3");
redisTemplate.opsForValue().multiSet(map);
redisTemplate.opsForValue().append("name5","heima");
}
@Test
public void testGet(){
String value = redisTemplate.opsForValue().get("name");
System.out.println(value);
String name = redisTemplate.opsForValue().get("name", 5, 7);
System.out.println(name);
List<String> keys = new ArrayList<>();
keys.add("name2");
keys.add("name3");
keys.add("name4");
List<String> values = redisTemplate.opsForValue().multiGet(keys);
for (String s : values) {
System.out.println(s);
}
Long size = redisTemplate.opsForValue().size("name");
System.out.println(size);
}
@Test
public void testIncrement(){
redisTemplate.opsForValue().set("age","18");
redisTemplate.opsForValue().increment("age");
System.out.println(redisTemplate.opsForValue().get("age"));
redisTemplate.opsForValue().increment("age",6);
System.out.println(redisTemplate.opsForValue().get("age"));
redisTemplate.opsForValue().decrement("age");
}
@Test
public void testDelete(){
redisTemplate.delete("name");
List<String> list = new ArrayList<>();
list.add("name2");
list.add("name3");
list.add("name4");
redisTemplate.delete(list);
}
}
TestRedisList
package com.ljx.springboot_redis;
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.SpringJUnit4ClassRunner;
import javax.swing.*;
import java.util.List;
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class TestRedisList {
@Autowired
private RedisTemplate<String,String> redisTemplate;
@Test
public void testAdd(){
redisTemplate.opsForList().leftPush("students","zhangshan");
redisTemplate.opsForList().leftPush("students","lishi","wangwu");
redisTemplate.opsForList().rightPush("students","zhangshan1");
redisTemplate.opsForList().rightPush("students","lishi1","wangwu1");
}
@Test
public void testFind(){
String students = redisTemplate.opsForList().index("students", 1);
System.out.println(students);
String students1 = redisTemplate.opsForList().index("students", -1);
System.out.println(students1);
List<String> students2 = redisTemplate.opsForList().range("students", 0, 2);
for (String s : students2) {
System.out.println(s);
}
}
@Test
public void testRemove(){
String s = redisTemplate.opsForList().leftPop("students");
String s1 = redisTemplate.opsForList().rightPop("students");
redisTemplate.opsForList().remove("students",2,"wangwu");
}
}
TestRedisHash
package com.ljx.springboot_redis;
import com.ljx.springboot_redis.uesr.Article;
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.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class TestRedisHash {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void testPut(){
Article article = new Article();
article.setTitle("title");
article.setCreateTime(new Date());
article.setAuthor("lixiang");
redisTemplate.opsForHash().put("article","1",article);
}
@Test
public void testGet(){
List<Article> articles = redisTemplate.opsForHash().values("article");
for (Article article : articles) {
System.out.println(article);
}
Map<String,Article> map = redisTemplate.opsForHash().entries("article");
for (Map.Entry<String, Article> entry : map.entrySet()) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
@Test
public void testDelete(){
redisTemplate.opsForHash().delete("article","1","2");
}
}
Article
package com.ljx.springboot_redis.uesr;
import javax.xml.crypto.Data;
import java.io.Serializable;
import java.util.Date;
public class Article implements Serializable {
private String author;
private Data createTime;
private String title;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Data getCreateTime() {
return createTime;
}
public void setCreateTime(Data createTime) {
this.createTime = createTime;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "Article{" +
"author='" + author + '\'' +
", createTime=" + createTime +
", title='" + title + '\'' +
'}';
}
public void setCreateTime(Date date) {
}
}
TestRedisSet
package com.ljx.springboot_redis;
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.SpringJUnit4ClassRunner;
import java.util.List;
import java.util.Set;
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class TestRedisSet {
@Autowired
private RedisTemplate<String,String> redisTemplate;
@Test
public void testAdd(){
redisTemplate.opsForSet().add("Students","zhangsan","lishi","wangwu","Zhangsan");
}
@Test
public void testFind(){
Set<String> students = redisTemplate.opsForSet().members("Students");
for (String student : students) {
System.out.println(student);
}
String students1 = redisTemplate.opsForSet().randomMember("Students");
System.out.println(students1);
List<String> list = redisTemplate.opsForSet().randomMembers("Students", 2);
for (String s : list) {
System.out.println(s);
}
}
@Test
public void testRemove(){
Long remove = redisTemplate.opsForSet().remove("Students", "zhangsan", "wangwu");
System.out.println(remove);
List<String> students = redisTemplate.opsForSet().pop("Students", 2);
for (String student : students) {
System.out.println(student);
}
}
@Test
public void testMoreSet(){
redisTemplate.opsForSet().add("names1","zhangsan","li","wangwu");
redisTemplate.opsForSet().add("names2","zhangsan","li","zhaoliu");
Set<String> intersect = redisTemplate.opsForSet().intersect("names1", "names2");
for (String s : intersect) {
System.out.println(s);
}
Set<String> union = redisTemplate.opsForSet().union("names1", "names2");
for (String s : union) {
System.out.println(s);
}
Set<String> difference = redisTemplate.opsForSet().difference("names2", "names1");
for (String s : difference) {
System.out.println(s);
}
}
}
TestRedisZSet
package com.ljx.springboot_redis;
import org.junit.Before;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.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.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Set;
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
class TestRedisZSet {
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Test
public void testAdd(){
redisTemplate.opsForZSet().add("student","wangwu",60);
redisTemplate.opsForZSet().add("student","lishi",100);
redisTemplate.opsForZSet().add("student","zhangshan",90);
}
@Test
public void testScore(){
redisTemplate.opsForZSet().incrementScore("student","wangwu",30);
redisTemplate.opsForZSet().incrementScore("student","wangwu",-50);
}
@Test
public void testFindOne(){
Double score = redisTemplate.opsForZSet().score("student", "wangwu");
System.out.println(score);
Long rank = redisTemplate.opsForZSet().rank("student", "zhangshan");
System.out.println(rank);
}
@Test
public void testFindList(){
Set<String> students = redisTemplate.opsForZSet().range("student",0,2);
for (String student : students) {
System.out.println(student);
}
System.out.println("-------------");
Set<ZSetOperations.TypedTuple<String>> student = redisTemplate.opsForZSet().rangeWithScores("student", 0, 2);
for (ZSetOperations.TypedTuple<String> stringTypedTuple : student) {
System.out.println(stringTypedTuple.getValue()+"同学,得了"+stringTypedTuple.getScore()+"分");
}
System.out.println("-----------------------------");
Set<String> students1 = redisTemplate.opsForZSet().rangeByScore("student",50,100);
for (String student1 : students1) {
System.out.println(student1);
}
System.out.println("-------------");
Set<ZSetOperations.TypedTuple<String>> student1 = redisTemplate.opsForZSet().rangeByScoreWithScores("student", 50, 100);
for (ZSetOperations.TypedTuple<String> stringTypedTuple : student1) {
System.out.println(stringTypedTuple.getValue()+"同学,得了"+stringTypedTuple.getScore()+"分");
}
}
@Test
public void testCount(){
Long student = redisTemplate.opsForZSet().zCard("student");
System.out.println(student);
Long count = redisTemplate.opsForZSet().count("student", 50, 100);
System.out.println(count);
}
@Test
public void testRemove(){
redisTemplate.opsForZSet().remove("student","zhangsan","lisi");
redisTemplate.opsForZSet().removeRange("student",0,1);
redisTemplate.opsForZSet().removeRangeByScore("student",70,90);
}
}