1. 正文
1. springboot连接redis
2. springboot使用场景
3. springboot连接redis集群。
4. redis的常见面试题。
2. springboot连接redis
使用redisTemplate该类可以存放任意类型的数据,但是该类型的数据必须实现序列,获取redis中对应的数据时,会进行反序列化。 如果使用RedisTemplate建议大家指定key,value,以及hashkey的序列化方式。
package com.ykq.config;
/**
* @Author 闫克起
* @Date 2021/4/15 16:16
* @Version 1.0
*/
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.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.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;
import java.time.Duration;
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
//比如验证码
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setConnectionFactory(factory);
//key序列化方式
template.setKeySerializer(redisSerializer);
//value序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
//value hashmap序列化
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解决乱码的问题),过期时间600秒
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(600)) //缓存过期10分钟 ---- 业务需求。
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))//设置key的序列化方式
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) //设置value的序列化
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}
3. springboot连接redis集群。
(1)哨兵
spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=192.168.213.188:26379
(2) 去中心化集群
spring.redis.cluster.nodes=192.168.213.188:8001,192.168.213.188:8002,192.168.213.188:8003,192.168.213.188:8004,192.168.213.188:8005,192.168.213.188:8006
6. springboot使用场景
(1)作为缓存。
1.为什么使用缓存?
减少数据库的访问频率。 提高数据的访问率。
2.什么样的数据适合放入缓存?
1.热点数据。 2. 修改频率比较低。3.安全系数低的。
缓存的原理:
如何使用缓存
(1)搭建一个springboot+mp的工程
(2)引入redis相关的依赖
(3)配置redis
(4)service代码
package com.ykq.service;
import com.ykq.dao.DeptDao;
import com.ykq.entity.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @Author 闫克起
* @Date 2021/4/15 16:07
* @Version 1.0
*/
@Service
public class DeptService {
@Resource
private DeptDao deptDao;
@Autowired
private RedisTemplate redisTemplate;
public Dept findById(Integer deptId){
//1.从缓存中查询该数据
Object o = redisTemplate.opsForValue().get("findById::" + deptId);
if(o!=null){//表示从缓存中获取该数据
return (Dept) o;
}
Dept dept = deptDao.selectById(deptId);
redisTemplate.opsForValue().set("findById::"+deptId,dept);//把查询的结果放入缓存
return dept;
}
//数据库和缓存同步问题!
public int delete(Integer deptId){
redisTemplate.delete("findById::"+deptId);//删除缓存
int i = deptDao.deleteById(deptId);
return i;
}
public int update(Dept dept){
redisTemplate.delete("findById::"+dept.getDeptId());//删除缓存
int i = deptDao.updateById(dept);
redisTemplate.opsForValue().set("findById::"+dept.getDeptId(),dept);
return i;
}
}
上面这些代码每次都要写很多与业务无关的一些非业务代码!
(1)使用aop来解决---->动态代理(动态代理的实现模式基于JDK动态代理)
https://blog.csdn.net/qq_39470733/article/details/77315010
(2)基于spring的缓存注解。
package com.ykq;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@MapperScan(basePackages = "com.ykq.dao")
@EnableCaching //开启缓存的注解
public class SpringbootRedis02Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootRedis02Application.class, args);
}
}
package com.ykq.service;
import com.ykq.dao.DeptDao;
import com.ykq.entity.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @Author 闫克起
* @Date 2021/4/15 16:07
* @Version 1.0
*/
@Service
public class DeptService {
@Resource
private DeptDao deptDao;
//该注解作用:会先查询缓存,如果缓存存在,则不会执行代码块。 如果缓存中不存在则执行该方法,并把该方法的返回值存放到redis中
@Cacheable(cacheNames = "findById",key = "#deptId") //缓存的key值 为findById
public Dept findById(Integer deptId){
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
Dept dept = deptDao.selectById(deptId);
return dept;
}
//数据库和缓存同步问题!
// beforeInvocation:是否在方法执行前就清空,缺省为 false,
// 如果指定为 true,则在方法还没有执行的时候就清空缓存。缺省情况下,如果方法执行抛出异常,则不会清空缓存。
@CacheEvict(cacheNames = "findById",key = "#deptId")
public int delete(Integer deptId){
int i = deptDao.deleteById(deptId);
return i;
}
//这个注解是必须执行方法体,而且会把方法体执行的结果放入到缓存中。 如果发生异常则不操作缓存。
@CachePut(cacheNames = "findById",key = "#dept.deptId")
public Dept update(Dept dept){
int i = deptDao.updateById(dept);
return dept;
}
}