电脑
intelliJ idea,jdk1.8,mysql
首先先下载免安装的绿色压缩包,地址是:https://github.com/MSOpenTech/redis/releases。下图红圈中的就是面安装的压缩包了。
解压之后文件目录如下:
双击redis-server.exe启动,启动后的界面如下图所示
注意点:当Redis后界面不能关闭,如果关闭了,Redis也就关闭了。所以有另外一种方式启动,就是变成服务。 就是在环境变量的系统变量Path中添加解压后的路径,然后打开cmd.exe界面输入redis-server.exe --service-install redis.windows.conf --loglevel verbose就能变成服务了。
现在我们继续在springboot项目(三)的基础上,再进行集成Redis。
pom.xml引入Redis相关jar包,配置为:
在application.yml配置文件中配置Redis相关的链接端口等信息,配置如下:#Redis配置 redis: host: 127.0.0.1 #edis服务器IP port: 6379 # Redis服务器连接端口 password: # 连接密码(默认为空) pool: max-active: 12 # 连接池最大连接数 max-wait: -1 # 连接池最大阻塞 max-idle: 12 # 连接池中的最大空闲连接 min-idle: 2 # 连接池中的最小空闲连接 timeout: 0 # 连接超时时间
编写Redis缓存服务,代码如下:import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.concurrent.TimeUnit; /** * Redis缓存服务 * Created by 30721 on 2019/7/7. */@Service public class RedisCacheService { @Resource private RedisTemplate
测试代码如下:import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; /** * Created by 30721 on 2019/7/7. */ @RunWith(SpringRunner.class) @SpringBootTest public class RedisTest { @Autowired private RedisCacheService redisCacheService; @Test public void test() { String key = 'key1'; //测试数据添加和获取 redisCacheService.set(key, 'hello'); System.out.println(redisCacheService.get(key)); //删除key redisCacheService.delete(key); System.out.println(redisCacheService.get(key)); //设置时间 redisCacheService.set(key, 'HELLO WORLD', 2L); System.out.println(redisCacheService.get(key)); try { Thread.sleep(2000L);//休眠2秒 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(redisCacheService.get(key)); } }
测试结果是:hellonullHELLO WORLDnull如下图: