這篇文章主要介紹springboot整合redis瞒窒,至于沒有接觸過redis的同學可以看下這篇文章:5分鐘帶你入門Redis闯睹。
引入依賴:
在pom文件中添加redis依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置數(shù)據(jù)源
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有密碼须蜗,配置下即可。經(jīng)過上述兩步的操作啄糙,你可以訪問redis數(shù)據(jù)了湃累。
數(shù)據(jù)訪問層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"));
}
}
啟動單元測試,你發(fā)現(xiàn)控制臺打印了:
forezp