Redis与SpringBoot整合

    xiaoxiao2022-07-05  171

    Redis与SpringBoot整合

    一、RedisTemplate 与 StringRedisTemplate对象使用

    Maven依赖:

    <!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>

    .yml配置:

    spring: ################################# --- Redis --- ################################# application: name: spring-boot-redis redis: host: 112.11.54.12 port: 9677 timeout: 20000ms database: 0 password: Passc0de1!! jedis: pool: max-active: 8 max-wait: -1ms max-idle: 8 min-idle: 0

    RedisConfig配置类:

    package com.config.redis; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import java.net.UnknownHostException; /** * Redis Config * By CHENYB Date 2019-05-22 */ @Configuration public class RedisConfig { @Bean @ConditionalOnMissingBean(name = "redisTemplate") public RedisTemplate<String, Object> redisTemplate( RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); template.setConnectionFactory(redisConnectionFactory); template.setKeySerializer(jackson2JsonRedisSerializer); template.setValueSerializer(jackson2JsonRedisSerializer); template.setHashKeySerializer(jackson2JsonRedisSerializer); template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } @Bean @ConditionalOnMissingBean(StringRedisTemplate.class) public StringRedisTemplate stringRedisTemplate( RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { StringRedisTemplate template = new StringRedisTemplate(); template.setConnectionFactory(redisConnectionFactory); return template; } }

    Redis工具类:https://blog.csdn.net/scdncby/article/details/90448953

    二、注解式

    Maven依赖(spring-boot-starter-data-redis更换为spring-boot-starter-redis):

    <!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency>

    .yml配置同上,RedisConfig配置类同上即可(如果不需要RedisTemplate对象,RedisConfig配置类可以不要)

    注意:需要启动类中开启SpringBoot缓存支持,在启动类中加入@EnableCaching注解标签(也可以一在配置类中开启此标签)

    缓存注解说明:

    @Cacheable:在方法执行前Spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据,若没有数据,调用方法返回结果数据并将结果数据放进缓存;@CachePut:无论怎样,都会将方法的返回值放到缓存中。@CachePut的属性与@Cacheable保持一致;@CacheEvict:将一条或多条数据从缓存中删除,建议配合持久化删除一同使用;@Caching:可以通过@Caching注解组合多个注解策略在一个方法上;

    缓存属性说明:

    value:对象对应缓存名称;key:存储在缓存中的键(如果参数是基本数据类型,可以用#+参数作为键,key的属性可以使用result. result代表方法返回对象;也可以套单引号像弱语言一样拼接;如果使用参数作为键,#+参数其中的参数名称要与实际参数保持一致);@Caching中可以组合cacheable,put,evint,但是参数都以数组形式配置执行策略

    例如:

    @CacheEvict(value="User",allEntries = true,beforeInvocation = true) 清除所有指定对象缓存

    @Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserRepository repository; @Override @Cacheable(value = "User") public List<User> getUsers() { System.out.println("没有出现SQL 就是缓存读取"); return this.repository.findAll(); } @Override @Cacheable(value = "User",key = "'uuid'+#id") public User findUser(Long id) { System.out.println("没有出现SQL 就是缓存读取"); return this.repository.findById( id ).orElse( new User() ); } @Override @Caching( cacheable = { @Cacheable(value = "User",key = "#result.id") }, put = { @CachePut(value = "User",key = "#result.id"), @CachePut(value = "User",key = "#result.id") } ) public User addUser(User u) { return this.repository.save( u ); } @Override @CacheEvict(value = "User",key = "#id") public void delUser(Long id) { this.repository.deleteById( id ); } }

    注意:如果需要最后的数据处理,或者缓存前数据处理,建议处理数据的方法和做缓存的方法分别处理,带有缓存注解的方法如果有对应的缓存数据可以错作,则会跳过方法直接调用缓存,直接返回不会走方法逻辑

     

     

     

    Mr.Chenyb  随笔记录,只为自己用着方便

    最新回复(0)