1.简介
Spring中常用Redis做数据库的缓存,第一次查询走数据库并缓存到redis,第二次查询由redis直接返回数据。
2.安装Redis
mac安装:
brew install redis
linux安装:
sudo apt-get install lsb-release curl gpg
curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
sudo chmod 644 /usr/share/keyrings/redis-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list
sudo apt-get update
sudo apt-get install redis
查询config文件在哪:
redis-cli INFO | grep config_file
通过config文件设置密码
#mac下
vim /opt/homebrew/etc/redis.conf
#linux下
vim /etc/redis/redis.conf
添加
requirepass 12345678
启动redis:
#linux下
systemctl restart redis-server
#mac下
brew services start redis
命令行测试redis已经启动:
redis-cli -a 12345678
127.0.0.1:6379> ping
PONG
查看所有key:
127.0.0.1:6379> keys *
1) "article::getArticles"
查看key对应的value:
127.0.0.1:6379> get article::getArticles
3. 拉起
pom.xml加入:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
application.yaml配置文件中加入:
spring:data:redis:host: 127.0.0.1port: 6379
添加Redis配置类:
java">@Configuration
@EnableCaching
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(factory);redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));return redisTemplate;}@Beanpublic RedisCacheManager redisCacheManager(RedisTemplate redisTemplate){RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((redisTemplate.getValueSerializer())));return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);}
}
测试基本功能:
java">@SpringBootTest
public class RedisTester {@Autowiredprivate RedisTemplate redisTemplate;@Autowiredprivate ArticlesMapper articlesMapper;@Testpublic void testSet(){//存入数据redisTemplate.boundValueOps("name").set("zhangsan");}@Testpublic void testGet(){//获取数据Object name = redisTemplate.boundValueOps("name").get();System.out.println("name = " + name);}@Testpublic void testReadSql(){List<Article> articles = articlesMapper.getArticles();Map<String ,String> map = articles.stream().collect(Collectors.toMap(article -> article.getId().toString(), article -> article.getText()));redisTemplate.opsForHash().putAll("test",map);Object test = redisTemplate.opsForHash().get("test", "82");System.out.println("test = " + test);}
}
实战添加注解:
java">@Cacheable(value = "article", key="'getArticles'")//第一次访问mysql,之后创建缓存,不再访问mysql
@Override
public Result getArticles() {...
}//数据未找到时不保存缓存,Cacheable返回值使用unless判断(返回使用),不能用condition(入参判断使用)
@Cacheable(value = "article", key="'article:' + #articleId",unless = "#result.getData() == null")
@Override
public Result getArticle(Integer articleId) {...return Result.ok(article);
}//数据变化时更新缓存,删除群缓存
@CachePut(value = "article",key = "'article:' + #article.id")
@CacheEvict(value= "article", key="'getArticles'")
@Override
public Result createArticle(Article article){...
}//数据变化时更新缓存,删除群缓存
@CachePut(value = "article",key = "'article:' + #article.id")
@CacheEvict(value= "article", key="'getArticles'")
@Override
public Result modifyArticle(Article article) {...
}//数据变化时更新缓存,删除群缓存
@Caching(evict = {@CacheEvict(value = "article", key="'article:' + #articleId"),@CacheEvict(value= "article", key="'getArticles'")
})
@Override
public Result deleteArticle(Integer articleId) {...
}