Redis与SpringBoot整合

14 篇文章 0 订阅
8 篇文章 0 订阅

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      # ip
    port: 9677              #端口号
    timeout: 20000          #最大超时
    database: 0             #使用数据库 0-15
    password: Passc0de1!!   #密码
  • 哨兵模式yml配置:
spring:
  redis:
##############################   ---   Redis哨兵模式   ---   ##############################
    database: 1             #对应数据库 0-15
    password: Passc0de1!!   #主从密码
    sentinel:               #哨兵配置
      master: chen-master  #检测的master节点名称
      nodes: 192.168.50.201:26379,192.168.50.202:26379,192.168.50.203:26379    #哨兵节点(ip:端口号‘,’分隔)
  • 集群模式yml配置:

spring:
  redis:
##############################   ---   Redis集群模式   ---   ##############################
    password: Passc0de1!!    #集群密码
    cluster:                 #集群配置
      nodes: 192.168.50.201:6379,192.168.50.202:6379,192.168.50.203:6379,192.168.50.204:6379,192.168.50.205:6379,192.168.50.206:6379    #集群节点(ip:端口号,‘,’分割)

连接池配置

spring:
#############################   ---   Redis连接池   ---   ##############################
  redis:
    jedis:
      pool:
        max-active: 8        #最大连接数
        max-wait: -1ms       #最大等待时常 -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注解标签(也可以一在配置类中开启此标签)

缓存注解说明:

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

缓存属性说明:

  1. value:对象对应缓存名称;
  2. key:存储在缓存中的键(如果参数是基本数据类型,可以用#+参数作为键,key的属性可以使用result. result代表方法返回对象;也可以套单引号像弱语言一样拼接;如果使用参数作为键,#+参数其中的参数名称要与实际参数保持一致);
  3. @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 );
    }
}
  • SpEL表达式 

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

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值