1.Jedis测试
1.1导入jar包
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>
</dependencies>
1.2修改redis.conf配置文件,使其能被其他主机连接
- 1.bind 127.0.0.1 -::1:注释掉
- 2.保护模式protected-mode:开发环境中要改成protected-mode no
1.3重启redis服务
- 主要要关掉虚拟机的防火墙。
systemctl status firewalld
:查看防火墙状态systemctl stop firewalld
:临时关闭防火墙disable firewalld.service
:永久禁用Linux的防火墙
1.4测试连接代码
public static void main(String[] args) {
//创建Jedis对象
Jedis jedis = new Jedis("192.168.92.130", 6379);
//测试
String result = jedis.ping();
System.out.println(result);
}
测试连接成功:
1.5Jedis常用操作
相关命令和API基本是对应的。
1.5.1Jedis-API: Key
jedis.set("k1", "v1");
jedis.set("k2", "v2");
jedis.set("k3", "v3");
Set<String> keys = jedis.keys("*");
System.out.println(keys.size());
for (String key : keys) {
System.out.println(key);
}
System.out.println(jedis.exists("k1"));
System.out.println(jedis.ttl("k1"));
System.out.println(jedis.get("k1"));
1.5.2Jedis-API: String
jedis.mset("str1","v1","str2","v2","str3","v3");
System.out.println(jedis.mget("str1","str2","str3"));
1.5.3Jedis-API: List
List<String> list = jedis.lrange("mylist",0,-1);
for (String element : list) {
System.out.println(element);
}
1.5.4Jedis-API: Set
jedis.sadd("orders", "order01");
jedis.sadd("orders", "order02");
jedis.sadd("orders", "order03");
jedis.sadd("orders", "order04");
Set<String> smembers = jedis.smembers("orders");
for (String order : smembers) {
System.out.println(order);
}
jedis.srem("orders", "order02");
1.5.5Jedis-API: hash
jedis.hset("hash1","userName","lisi");
System.out.println(jedis.hget("hash1","userName"));
Map<String,String> map = new HashMap<String,String>();
map.put("telphone","13810169999");
map.put("address","atguigu");
map.put("email","[email protected]");
jedis.hmset("hash2",map);
List<String> result = jedis.hmget("hash2", "telphone","email");
for (String element : result) {
System.out.println(element);
}
1.5.6Jedis-API: zset
jedis.zadd("zset01", 100d, "z3");
jedis.zadd("zset01", 90d, "l4");
jedis.zadd("zset01", 80d, "w5");
jedis.zadd("zset01", 70d, "z6");
Set<String> zrange = jedis.zrange("zset01", 0, -1);
for (String e : zrange) {
System.out.println(e);
}
1.6.模拟手机验证码
1.需求:
- 输入手机号,点击发送后随即生成6为数字码,2分钟有效
- 输入验证码,点击验证,返回成功或失败
- 每个手机号每天只能输入3次。
2.相关代码
public class PhoneCode {
public static void main(String[] args) {
//模拟发送验证码
//sendCode("1234567890");
//校验验证码
verifyCode("1234567890", "273938");
}
/**
* 1.生成6为随机码
* @return
*/
public static String getCode(){
Random random = new Random();
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < 6; i++) {
int code = random.nextInt(10);
sb.append(code);
}
return sb.toString();
}
/**
* 2.模拟发送验证码:
* 每个手机每天只能发送三次,验证码放到redis中,设置过期时间
*/
public static void sendCode(String phone){
//1.创建Jedis对象
Jedis jedis = new Jedis("192.168.92.130", 6379);
//2.拼接key
//手机发送次数key
String countKey = "VerifyCode"+phone+":count";
//验证码key
String codeKey = "VerifyCode"+phone+":code";
//3.每个手机每天只能发送三次
String count = jedis.get(countKey);
if(count == null){
//没有发送次数,第一次发送,设置发送次数1
jedis.setex(countKey, 24*60*60, "1");
//4.发送的验证码次数不超过3次时,执行该步骤:放到redis中
String code = getCode();
jedis.setex(codeKey, 24*60*60, code);
}else if(Integer.parseInt(count) <= 2){
//发送次数+1
jedis.incr(countKey);
//4.发送的验证码次数不超过3次时,执行该步骤:放到redis中
String code = getCode();
jedis.setex(codeKey, 24*60*60, code);
}else if(Integer.parseInt(count) > 2){
//发送3次了
System.out.println("已经发送3次验证码,达到上限。");
jedis.close();
}
jedis.close();
}
/**
* 3.验证校验码
* @param phone
* @param code
*/
public static void verifyCode(String phone, String code){
//1.创建Jedis对象
Jedis jedis = new Jedis("192.168.92.130", 6379);
//2.验证码key
String codeKey = "VerifyCode"+phone+":code";
String redisCode = jedis.get(codeKey);
//3.判断
if(code.equals(redisCode)){
System.out.println("验证成功");
}else{
System.out.println("校验失败");
}
jedis.close();
}
}
2.SpringBoot整合Redis
Spring Boot整合Redis非常简单,只需要按如下步骤整合即可
2.1.先新建一个SpringBoot项目
注意:要创建一个web项目。
2.2.添加相关依赖
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- spring2.X集成redis所需common-pool2连接池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.0</version>
</dependency>
2.3.配置application.properties文件
#Redis服务器地址
spring.redis.host=192.168.140.136
#Redis服务器连接端口
spring.redis.port=6379
#Redis数据库索引(默认为0)
spring.redis.database= 0
#连接超时时间(毫秒)
spring.redis.timeout=1800000
#连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=20
#最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-wait=-1
#连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=5
#连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0
2.4.添加redis配置类
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setConnectionFactory(factory);
//key序列化方式
template.setKeySerializer(redisSerializer);
//value序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
//value hashmap序列化
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解决乱码的问题),过期时间600秒
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(600))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}
2.5.测试方法
@RestController
@RequestMapping("/redisTest")
public class RedisTestController {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping
public String testRedsi(){
//设置值到redis
redisTemplate.opsForValue().set("name", "lucy");
//从redis中获取值
String name = (String)redisTemplate.opsForValue().get("name");
return name;
}
}