1、在pom文件中添加redis依赖:
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、application.properties中配置数据源
# redis
spring.redis.host=62.234.95.122
spring.redis.port=6379
#spring.redis.password=
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.timeout=5000
spring.redis.database=1
3、数据访问层dao
@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);
}
}
4、单元测试
@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","yql");
redisDao.setKey("age","18");
logger.info(redisDao.getValue("name"));
logger.info(redisDao.getValue("age"));
}
}
启动单元测试,控制台打印了:
yql
18
项目地址:https://github.com/muyi25/springBoot 项目名:spring-boot-redis
网友评论