直接上代码吧
1.首先pom中加入
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
2.然后
配置文件中
redis: host: 127.0.0.1 port: 6379 timeout: 1000 pool: max-active: 8 min-idle: 0 max-idle: 8 max-wait: -1
3.然后
就是类似的工具类
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Repository; @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,5, TimeUnit.MINUTES);//5分钟过期 ops.set(key, value); } public String getValue(String key){ ValueOperations<String, String> ops = this.template.opsForValue(); return ops.get(key); } }
4.测试类
import com.example.demo.com.cwh.springbootRedis.dao.RedisDao; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class DemoApplicationTests { @Test public void contextLoads() { } public static Logger logger= LoggerFactory.getLogger(DemoApplicationTests.class); @Autowired RedisDao redisDao; @Test public void testRedis(){ redisDao.setKey("name","cwh"); redisDao.setKey("age","25"); logger.info(redisDao.getValue("name")); logger.info(redisDao.getValue("age")); logger.info("----------------------------------"); } }
最后你运行是不是发现报错了啊,去把本地的redis服务开了切换到redis根目录,然后用命令redis-server.exe redis.windows.conf,再运行控制台输出
cwh
25
----------------------------------
ok!