zoukankan      html  css  js  c++  java
  • 企业级 SpringBoot 教程 (九)springboot整合Redis

    引入依赖:

    在pom文件中添加redis依赖:

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

    配置数据源

    spring.redis.host=localhost
    spring.redis.port=6379
    #spring.redis.password=
    spring.redis.database=1
    spring.redis.pool.max-active=8
    spring.redis.pool.max-wait=-1
    spring.redis.pool.max-idle=500
    spring.redis.pool.min-idle=0
    spring.redis.timeout=0
    

    如果你的redis有密码,配置下即可。经过上述两步的操作,你可以访问redis数据了。

    数据访问层dao

    通过redisTemplate来访问redis.

    @Repository
    public class RedisDao {
    
        @Autowired
        private StringRedisTemplate template;
    
        public  void setKey(String key,String value){
            ValueOperations<String, String> ops = template.opsForValue();
            ops.set(key,value,1, TimeUnit.MINUTES);//1分钟过期
        }
    
        public String getValue(String key){
            ValueOperations<String, String> ops = this.template.opsForValue();
            return ops.get(key);
        }
    }
    

    单元测试

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class SpringbootRedisApplicationTests {
    
        public static Logger logger= LoggerFactory.getLogger(SpringbootRedisApplicationTests.class);
        @Test
        public void contextLoads() {
        }
    
        @Autowired
        RedisDao redisDao;
        @Test
        public void testRedis(){
            redisDao.setKey("name","forezp");
            redisDao.setKey("age","11");
            logger.info(redisDao.getValue("name"));
            logger.info(redisDao.getValue("age"));
        }
    }

    启动单元测试,你发现控制台打印了:

    forezp

    11

    单元测试通过;

    资料和源码来源地址

  • 相关阅读:
    c#设计模式(1)——单例模式
    Javascript变量
    悲观锁和乐观锁
    NestJs 环境 配置
    分布式查询
    Git hub 忽略 文件 、文件夹
    ES6 基础 二
    ES6 基础 一
    invalid credential, access_token is invalid or not latest hint(微信 上传图片返回 error)
    nodejs 入门一(环境及插件)
  • 原文地址:https://www.cnblogs.com/xiamudaren/p/8403686.html
Copyright © 2011-2022 走看看