Java工具篇之Redis的简单使用
1、下载安装
Redis官网下载的是linux版的,windows版本的下载地址点这里。java
下载解压以后目录结构长这样子linux
打开redis.windows.conf文件,设置密码。git
设置完成以后,须要执行redis-server.exe redis.windows.conf,此时密码已经生效。github
2、整合redis
保持redis的窗口打开状态,关闭窗口就中止redis了,若是有须要也能够注册成服务,此处再也不赘述。web
首先须要引入jar包文件redis
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
而后写一个测试类检验一下是否能够正常使用了,代码以下:spring
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import redis.clients.jedis.Jedis; /** * @Author: SGdan_qi * @Date: 2020.05.09 * @Version: 1.0 */ @RestController public class TestController { @GetMapping("/test") public String test() { try { //链接本地的 Redis 服务 Jedis jedis = new Jedis("localhost"); jedis.auth("root"); System.out.println("链接成功"); //设置 redis 字符串数据 jedis.set("balance", "100w"); // 获取存储的数据并输出 System.out.println("您的余额为: "+ jedis.get("balance")); } catch (Exception e) { e.printStackTrace(); } return "success"; } }
最后看一下运行结果windows
3、RedisTemplate类
RedisTemplate是Spring Data Redis提供的最高级的抽象客户端,能够直接经过RedisTemplate进行多种操做,所以在开发中,通常都是使用此封装类来进行操做。服务器
首先须要引入jar包app
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
而后配置application.yml文件
spring: redis: # Redis服务器地址 host: 127.0.0.1 # Redis服务器链接端口 port: 6379 # Redis服务器链接密码(默认为空) password: root # 链接池最大链接数(使用负值表示没有限制) jedis: pool: max-active: 8 # 链接池最大阻塞等待时间(使用负值表示没有限制) max-wait: -1 # 链接池中的最大空闲链接 max-idle: 8 # 链接池中的最小空闲链接 min-idle: 0
写个测试类测试一下
@Autowired private RedisTemplate<String,String> redisTemplate; @GetMapping("/test") public String test() { try { redisTemplate.opsForValue().set("balance1","100w"); System.out.println(redisTemplate.opsForValue().get("balance1")); } catch (Exception e) { e.printStackTrace(); } return "success"; }
最后运行一下查看结果