前言
应用系统需要通过Cache来缓存不经常改变得数据来提高系统性能和增加系统吞吐量,避免直接访问数据库等低速存储系统。缓存的数据通常存放在访问速度更快的内存里或者是低延迟存取的存储器,服务器上。应用系统缓存,通常有如下作用:缓存web系统的输出,如伪静态页面。缓存系统的不经常改变的业务数据,如用户权限,字典数据.配置信息等
大家都知道springBoot项目都是微服务部署,A服务和B服务分开部署,那么它们如何更新或者获取共有模块的缓存数据,或者给A服务做分布式集群负载,如何确保A服务的所有集群都能同步公共模块的缓存数据,这些都涉及到分布式系统缓存的实现。(ehcache可以通过Terracotta组件一个缓存集群,这个暂时不讲)
但是ehcache的设计并不适合做分布式缓存,所以今天用redis来实现分布式缓存。
架构图:
一二级缓存服务器
使用Redis缓存,通过网络访问还是不如从内存中获取性能好,所以通常称之为二级缓存,从内存中取得的缓存数据称之为一级缓存。当应用系统需要查询缓存的时候,先从一级缓存里查找,如果有,则返回,如果没有查找到,则再查询二级缓存,架构图如下
Spring Boot 2 自带了前面俩种缓存的实现方式,本文将简单实现第三种,高速一二级缓存实现
Redis分布式缓存
引入redis的starter
配置Redis
在application.yml中配置redis信息
spring: redis: database: 0 host: 192.168.0.146 port: 6379 timeout: 5000
其他相关配置
# Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=127.0.0.1 # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password= # 连接池最大连接数(使用负值表示没有限制) 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=0
配置Redis缓存序列化机制
有的时候需要将对象存进redis(例如一个JavaBean对象),但是如果对象不是可Serializable的,因此需要让JavaBean对象实现Serializable接口
public class UserPO implements Serializable {
如果只是让JavaBean实现Serializable接口也是可以存储的,但是并不好看,那么能不能将JavaBean弄成Json的样式放进redis呢。直接的方式就是自己转换,但是未免有点麻烦,那就只能修改RedisTemplate的序列化机制了,在配置类中配置上序列化的方法即可
@Bean public RedisTemplateredisTemplate(RedisConnectionFactory factory) { RedisTemplate template = new RedisTemplate(); template.setConnectionFactory(factory); Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jacksonSeial.setObjectMapper(om); // 值采用json序列化 template.setValueSerializer(jacksonSeial); //使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(jacksonSeial); template.afterPropertiesSet(); return template; }
自定义CacheManager
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
RedisConfig完整代码
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.lang.reflect.Method;
import java.net.UnknownHostException;
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate template = new RedisTemplate();
// 配置连接工厂
template.setConnectionFactory(factory);
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
// 值采用json序列化
template.setValueSerializer(jacksonSeial);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();
return template;
}
@Bean
public KeyGenerator myKeyGenerator(){
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
}
使用Redi缓存注解
service:
@CachePut(value = "user",key = "'user_'+#result.id")
public UserPO save(UserPO po) {
userJpaMapper.save(po);
return po;
}
@CachePut(value = "user",key = "'user_'+#result.id")
public UserPO update(UserPO po) {
System.out.println("数据库更新");
userMapper.update(po);
return po;
}
@Cacheable(value = "user", key = "'user_'+#id")
public UserPO getUser(Integer id){
System.out.println("访问数据库:"+id);
return userJpaMapper.getOne(id);
}
@CacheEvict(value = "user", key = "'user_'+#id")
public void delete(Integer id) {
userJpaMapper.deleteById(id);
}
测试类:
@Test
void contextLoads() {
Integer id = 2;
UserPO user1 = userService.getUser(id);
System.out.println("第一次查询:"+user1.getUserName());
UserPO user2 = userService.getUser(id);
System.out.println("第二次查询:"+user2.getUserName());
}
测试结果:第一次查询的时候访问了数据库,第二次查询的时候并没有访问数据库
通过redis-cli 可以查看到数据已经保存到了redis上面
测试类:
@Test
void updataUser() {
Integer id = 4;
UserPO user1 = userService.getUser(id);
System.out.println("第一次查询:"+user1.getUserName()+", 年龄:"+user1.getAge());
user1.setAge(60);
userService.update(user1);
UserPO user2 = userService.getUser(id);
System.out.println("第二次查询:"+user2.getUserName()+", 年龄:"+user2.getAge());
}
测试结果:
Redis工具类(redisUtil.java)
1.在RedisConfig中定义redisTemplate操作对象
@Bean public HashOperationshashOperations(RedisTemplate redisTemplate) { return redisTemplate.opsForHash(); } @Bean public ValueOperations valueOperations(RedisTemplate redisTemplate) { return redisTemplate.opsForValue(); } @Bean public ListOperations listOperations(RedisTemplate redisTemplate) { return redisTemplate.opsForList(); } @Bean public SetOperations setOperations(RedisTemplate redisTemplate) { return redisTemplate.opsForSet(); } @Bean public ZSetOperations zSetOperations(RedisTemplate redisTemplate) { return redisTemplate.opsForZSet(); }
2.在redisUtil工具类中使用这些对象,并构建其操作方法
package com.meng.demo.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private ValueOperations valueOperations;
@Autowired
private HashOperations hashOperations;
@Autowired
private ListOperations listOperations;
@Autowired
private SetOperations setOperations;
@Autowired
private ZSetOperations zSetOperations;
public boolean expire(String key,long time){
try {
if(time>0){
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long getExpire(String key){
return redisTemplate.getExpire(key,TimeUnit.SECONDS);
}
public boolean hasKey(String key){
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void del(String ... key){
if(key!=null&&key.length>0){
if(key.length==1){
redisTemplate.delete(key[0]);
}else{
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
public boolean set(String key,Object value) {
try {
valueOperations.set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean set(String key,Object value,long expireTime){
try {
if(expireTime > 0){
valueOperations.set(key, value, expireTime, TimeUnit.SECONDS);
}else{
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public Object get(String key){
return key==null ? null:valueOperations.get(key);
}
public long incr(String key, long delta){
if(delta<0){
throw new RuntimeException("递增因子必须大于0");
}
return valueOperations.increment(key, delta);
}
public long decr(String key, long delta){
if(delta<0){
throw new RuntimeException("递减因子必须大于0");
}
return valueOperations.increment(key, -delta);
}
public Object hget(String key,String item){
return hashOperations.get(key, item);
}
public Map hmget(String key){
return hashOperations.entries(key);
}
public boolean hmset(String key, Map map){
try {
hashOperations.putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hmset(String key, Map map, long time){
try {
hashOperations.putAll(key, map);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hset(String key,String item,Object value) {
try {
hashOperations.put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hset(String key,String item,Object value,long time) {
try {
hashOperations.put(key, item, value);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void hdel(String key, Object... item){
hashOperations.delete(key,item);
}
public boolean hHasKey(String key, String item){
return hashOperations.hasKey(key, item);
}
public double hincr(String key, String item,double by){
return hashOperations.increment(key, item, by);
}
public double hdecr(String key, String item,double by){
return hashOperations.increment(key, item,-by);
}
public Set
3.测试
@Test
void test01(){
redisUtil.set("meng","yang");
Object key = redisUtil.get("meng");
System.out.println(key);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



