First, add the Maven Dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.1.3.RELEASE</version> </dependency>
Two .application.yml configure redis configuration
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 is not explicit to load the driver, if the driver package in line with SPI mode will automatically load
means that the program will automatically go to find out if there is a project-driven, of course, if there is no natural drive is not connected
Third, write a configuration class redis
The default is to use the JDK redis serialized manner.
JdkSerializationRedisSerializer
After saving the entity, the entity information garbled in Redis, redis need to modify the default serialization, configuration files created 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; } }
Fourth, the use of annotations ways to use 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; } }