springboot+redis整合

前言

趁项目空余时间,总结一下springboot与redis整合的相关注意事项和踩过的坑。

Redis简介

Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库。Redis 与其他 key - value 缓存产品有以下三个特点:
1.Redis支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用。
2.Redis不仅仅支持简单的key-value类型的数据,同时还提供list,set,zset,hash等数据结构的存储。
3.Redis支持数据的备份,即master-slave模式的数据备份。
Redis 优势:
1.性能极高 – Redis能读的速度是110000次/s,写的速度是81000次/s 。
2.丰富的数据类型 – Redis支持二进制案例的 Strings, Lists, Hashes, Sets 及 Ordered Sets 数据类型操作。
3.原子 – Redis的所有操作都是原子性的,意思就是要么成功执行要么失败完全不执行。单个操作是原子性的。多个操作也支持事务,即原子性,通过MULTI和EXEC指令包起来。丰富的特性 – Redis还支持 publish/subscribe, 通知, key 过期等等特性。

pom文件

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

yml文件中redis配置

redis:
    database: 3 # Redis数据库索引(默认为0)
    host:  192.168.7.109 #(改成自己想连接的redis地址) # Redis服务器地址
    port: 6379 # Redis服务器连接端口
    password: 123456 # Redis服务器连接密码(默认为空)
    pool:
      max-active: 1000 # 连接池最大连接数(使用负值表示没有限制)
      max-idle: 10 # 连接池中的最大空闲连接
      max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
      min-idle: 0 # 连接池中的最小空闲连接
    timeout: 5000 # 连接超时时间(毫秒)

redis配置文件

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.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Component;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(obj.toString());
            }
            return sb.toString();
        };
    }

    @SuppressWarnings("rawtypes")
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        //设置缓存过期时间
        rcm.setDefaultExpiration(60);//秒
        return rcm;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public RedisTemplate<String, String> redisJacksonTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);

        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.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    //=====下面两个bean是订阅队列的写法,只是个例子,可以根据具体需求编写=====
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //订阅了一个叫chat 的通道
        container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
        //这个container 可以添加多个 messageListener
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(MessageReceiver receiver) {
        //这个地方 是给messageListenerAdapter 传入一个消息接受的处理器,利用反射的方法调用“receiveMessage”
        //也有好几个重载方法,这边默认调用处理器的方法 叫handleMessage 可以自己到源码里面看
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

    /**
     * redis 消息处理器
     */
    @Component
    public class MessageReceiver {

        /**
         * 接收消息的方法
         */
        public void receiveMessage(String message) {
            System.out.println(message);
        }

    }
    //=====上面两个bean是订阅队列的写法,只是个例子,可以根据具体需求编写=====
}
@Service
public class StudentServiceImpl {
    @Autowired
    private StudentRepository studentRepository;
    @Autowired
    private RedisTemplate redisTemplate;

 public void set(Student student) {
        String key = CacheUtil.getStudentKey(student.getId());
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 1.1以字符串形式存到redis中
            redisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(student));
            // 1.2过期时间 -- 键 时间 单位 (10分钟过期)
            redisTemplate.expire(key, 10, TimeUnit.MINUTES);

            // 1.3redis中获取学生信息
            Object studentInfo = redisTemplate.opsForValue().get(key);

            // 2.1以hash的形式存到redis中
            Map<String, Object> student1 = new HashMap<>();
            student1.put("id", student.getId());
            student1.put("age", student.getAge());
            student1.put("name", student.getName());
            redisTemplate.opsForHash().putAll(key, student1);
            redisTemplate.expire(key, 10, TimeUnit.MINUTES);

            // 2.2从redis中获取学生信息
            Map<String, Object> stu = redisTemplate.opsForHash().entries(key);

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

util工具类

public class CacheUtil {
    private static final String PREFIX = "student:";

    /**
     * 用学生信息
     */
    public static String getStudentKey(Integer studentId) {
        return PREFIX + "student:" + studentId;
    }
}
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值