• SpringBoot集成redis缓存


    1.使用Spring-data包为redis客户端连接工具

    在pom文件中添加以下依赖:

        <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
                <exclusions>
                    <exclusion>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-logging</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    

    2.添加redis相关配置

    在application.properties中添加以下配置

    # Redis数据库索引(默认为0)
    spring.redis.database=0
    # Redis服务器地址
    spring.redis.host=xxx.xxx.xxx.xxx
    # Redis服务器连接端口
    spring.redis.port=xxxx
    # Redis服务器连接密码(默认为空)
    spring.redis.password=xxxxxx
    # 连接池最大连接数(使用负值表示没有限制)
    spring.redis.pool.max-active=8
    # 连接池最大阻塞等待时间(使用负值表示没有限制)
    spring.redis.pool.max-wait=-1
    # 连接池中的最大空闲连接
    spring.redis.pool.max-idle=8
    # 连接池中的最小空闲连接
    spring.redis.pool.min-idle=0
    # 连接超时时间(毫秒)
    spring.redis.timeout=0
    

    3.添加redisTemplate的bean

    添加配置类,代码如下:

    @Configuration
    public class RedisConfig {
    
        @Autowired
        JedisConnectionFactory jedisConnectionFactory;
    
        /**
         * @return redisTemplate 相当于xml中的bean
         */
        @Bean
        RedisTemplate<String, Object> redisTemplate(){
            RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
            redisTemplate.setConnectionFactory(jedisConnectionFactory);
            return redisTemplate;
        }
    
    }
    

    4.测试redis是否可用

    在test文件中添加以下单元测试内容,如测试通过则redis配置成功:

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class RedisTest {
    
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
    
        @Test
        public void redisTest(){
            List<String> nameList= new ArrayList<>();
            nameList.add("name1");
            nameList.add("name2211");
            redisTemplate.opsForValue().set("name",  "demoName");
            redisTemplate.opsForValue().set("nameList", nameList);
            Assert.assertEquals(redisTemplate.opsForValue().get("name"), "demoName");
            System.out.printf(redisTemplate.opsForValue().get("nameList").toString());
    
        }
    }
    
  • 相关阅读:
    使用JQuery+HTML写一个简单的后台登录页面,加上对登录名和密码的前端校验。
    Shiro入门3
    Shiro入门2
    Shiro入门1
    Spring+SpringMVC+Mybatis整合 pom示例
    IO(1)----File类
    集合(3)—— Map
    集合(3)—— Set
    集合(2)——List集合
    集合(1)
  • 原文地址:https://www.cnblogs.com/vitasyuan/p/9128017.html
Copyright © 2020-2023  润新知