企業級 SpringBoot 教程 (九)springboot整合Redis

引入依賴:

在pom文件中添加redis依賴:java

<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數據了。redis

數據訪問層dao

經過redisTemplate來訪問redis.spring

@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

單元測試經過分佈式

Spring Cloud大型企業分佈式微服務雲架構源碼請加企鵝求求:一七九一七四三三八零spring-boot

相關文章
相關標籤/搜索