• Spring Boot 中 Redis 的使用


    整合 Redis 哨兵模式

    引入依赖

    pox.xml 中引入 org.apache.commons:commons-pool2org.springframework.boot:spring-boot-starter-data-redis 依赖

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    

    相关配置

    application.yml 中添加 redis 及哨兵集群的配置

    spring:
       redis:
        lettuce:
          pool:
            # 最大连接数
            max-active: 8
            # 最大空闲连接数
            max-idle: 8
            # 最大阻塞等待时间(使用负值表示没有限制)
            max-wait: -1ms
            # 最小空闲连接数
            min-idle: 0
        sentinel:
          # 哨兵集群主节点名
          master: mymaster
          # 哨兵集群各节点
          nodes: {ip}:{port}, {ip}:{port}, {ip}:{port}
    

    使用 Redis

    注意:写入缓存的数据(如实体类)需要实现序列化,否则向 Redis 中存取数据会抛出异常

    这里只简单实现对 Redis 的增删改查操作

    创建 RedisService

    public interface RedisService {
    
        /**
         * 存储缓存
         * @param key
         * @param value
         * @param seconds
         */
        void set(String key, Object value, long seconds);
    
        /**
         * 获取缓存
         * @param key
         * @return
         */
        Object get(String key);
    
        /**
         * 删除缓存
         * @param key
         */
        boolean del(String key);
    }
    

    创建 RedisServiceImpl

    @Service
    public class RedisServiceImpl implements RedisService {
    
        @Autowired
        private RedisTemplate redisTemplate;
    
        @Override
        public void set(String key, Object value, long seconds) {
            redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
        }
    
        @Override
        public Object get(String key) {
            return redisTemplate.opsForValue().get(key);
        }
    
        @Override
        public boolean del(String key) {
            return redisTemplate.delete(key);
        }
    }
    

    解决序列化 Redis key-value 乱码

    spring-data-redisRedisTemplate<K, V> 模板类在操作 redis 时默认使用 JdkSerializationRedisSerializer 来进行序列化,如下:

    private boolean enableDefaultSerializer = true;
    private RedisSerializer<?> defaultSerializer = new JdkSerializationRedisSerializer();
    private RedisSerializer keySerializer = null;
    private RedisSerializer valueSerializer = null;
    private RedisSerializer hashKeySerializer = null;
    private RedisSerializer hashValueSerializer = null;
    

    创建 RedisListenerConfig 配置类

    @Configuration
    public class RedisListenerConfig {
    
        @Bean
        RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
    
            RedisMessageListenerContainer container = new RedisMessageListenerContainer();
            container.setConnectionFactory(connectionFactory);
            return container;
        }
    
        @Bean(name="redisTemplate")
        public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
            RedisTemplate<String, String> template = new RedisTemplate<>();
            RedisSerializer<String> redisSerializer = new StringRedisSerializer();
            template.setConnectionFactory(factory);
            template.setKeySerializer(redisSerializer);
            template.setValueSerializer(redisSerializer);
            template.setHashValueSerializer(redisSerializer);
            template.setHashKeySerializer(redisSerializer);
            return template;
        }
    }
    

    实现共享 Session

    引入依赖

    pom.xml 中添加 spring-session-data-redis 依赖

    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-data-redis</artifactId>
    </dependency>
    

    相关配置

    创建 RedisConfiguration 配置类

    import org.springframework.context.annotation.Configuration;
    import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
    
    @Configuration
    @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60 * 60 * 24)
    public class RedisConfiguration {
    
    }
    

    Controller

    创建存取 session 的接口

    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.servlet.http.HttpSession;
    
    @RestController
    public class IndexController {
    
        @GetMapping(value = "put")
        public String putSession(HttpSession session) {
            session.setAttribute("userId", "2384783434");
            return "ok";
        }
    
        @GetMapping(value = "get")
        public String getSession(HttpSession session) {
            return (String) session.getAttribute("userId");
        }
    
    }
    

    测试共享 Session

    分别启动两次项目,第一次启动项目设置端口为 80,第二次启动项目设置端口为 81

    默认情况下,Intellij IDEA 不允许同时启动两个相同的项目,需要在 Run/Debug Configurations 页面中设置允许同时运行多个相同的项目,如图所示,勾选 Allow parallel run 选项:

    《Spring Boot 中 Redis 的使用》

    最后在浏览器中先后访问 http://localhost/puthttp://localhost:81/get

  • 相关阅读:
    centos7下git服务器端搭建(转)
    IDEA各个版本激活(亲测有效,永久有效)(转)
    维护贴--linux下 mysql数据库的备份和还原 (转)
    维护贴--验证可用--mysql给root开启远程访问权限,修改root密码(转)
    开通mysql root 用户远程访问权限(转)
    安装mysql时包冲突解决方法
    mysql5.5 for linux 安装(转)
    Centos中iptables和firewall防火墙开启、关闭、查看状态、基本设置等(转)
    一个div宽度不固定的左右居中效果
    多行文字在一个div中上下左右居中
  • 原文地址:https://www.cnblogs.com/antoniopeng/p/12687410.html
Copyright © 2020-2023  润新知