Spring boot 2.x 中使用redis
一、添加Maven 依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.1.3.RELEASE</version> </dependency>
二.application.yml 中配置 redis 相关配置
spring: datasource: url: jdbc:mysql://localhost:3306/order?serverTimezone=GMT%2B8&characterEncoding=UTF-8 username: root password: xxxxxx redis: host: ip database: 0 port: 6379 password:
jdbc4.0 是不用显式的去加载驱动,如果驱动包符合 SPI 模式就会自动加载
就是说程序会自动去项目中查找是否有驱动,当然没有驱动的话自然是连接不了的
三、写一个 redis 配置类
redis 默认的是使用JDK 的序列化方式。
JdkSerializationRedisSerializer
当保存实体后,Redis 中的实体信息乱码,需要修改redis 默认的序列化方式,创建RedisConfig 配置文件
@Configuration public class RedisConfig { //设置过期时间 public static Duration liveTime = Duration.ofDays(1); @Bean public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory){ RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(liveTime) .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())) .disableCachingNullValues(); RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory) .cacheDefaults(cacheConfiguration).transactionAware().build(); return redisCacheManager; } @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate<String, Object> template = new RedisTemplate(); template.setConnectionFactory(redisConnectionFactory); //细化序列化 template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); //修改默认序列化器 /* Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class); template.setDefaultSerializer(serializer);*/ return template; } }
四、使用注解的方式使用Redis
@Service public class EmpService { @Autowired private EmpMapper empMapper; @Cacheable(cacheNames = {"emp"}) public Emp getEnp(int id){ return empMapper.getEmpById(id); } @CachePut public int insertEmp(Emp emp){ return empMapper.insertEmp(emp); } @CacheEvict(beforeInvocation = false,value = "emp") public int delEmp(int id){ empMapper.delEmp(id); return 1; } @CachePut(key = "#p0.id",value = "emp") public Emp updateEmp(Emp emp){ empMapper.updateEmp(emp); return emp; } }