zoukankan      html  css  js  c++  java
  • SpringBoot非官方教程 | 第九篇: springboot整合Redis

    转载请标明出处:
    原文首发于:https://www.fangzhipeng.com/springboot/2017/07/11/springboot9-redis/
    本文出自方志朋的博客

    这篇文章主要介绍springboot整合redis,至于没有接触过redis的同学可以看下这篇文章:5分钟带你入门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

    单元测试通过;

    源码下载:https://github.com/forezp/SpringBootLearning

    参考资料

    messaging-redis


    扫码关注公众号有惊喜

    (转载本站文章请注明作者和出处 方志朋的博客

  • 相关阅读:
    Dos命令大全(收藏)
    asp.net读写Cookies
    asp.net文件下载
    使用存储过程分页
    (十)死锁检测算法
    poj1664
    一席话惊醒梦中人
    深入了解scanf()/getchar()和gets()/cin等函数
    小结《malloc与new之区别》
    (六)文件管理
  • 原文地址:https://www.cnblogs.com/forezp/p/9852136.html
Copyright © 2011-2022 走看看