jedis是Java用来链接redis的一个工具,可以通过jedis在Java程序中操作redis。
修改配置文件
首先外部需要访问虚拟机中的redis,而redis默认是只让本机访问的,需要在redis.conf中注释掉bind 127.0.0.1 ,然后将protected-mode设置为no。注意,配置文件修改之后需要重启redis才能生效
引入相关依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.0.1</version>
</dependency>
创建测试工程
public class JedisTest {
public static void main(String[] args) {
//第一个参数为IP,第二个参数为redis端口号,默认是6379
Jedis jedis = new Jedis("192.168.200.130",6379);
String value = jedis.ping();
System.out.println(value); //成功返回pong
jedis.close(); //使用完记得关闭
}
}
key键操作
@Test
public void keyTest(){
Jedis jedis = new Jedis("192.168.200.130",6379);
Set<String> keys = jedis.keys("*");
keys.forEach(System.out::println);
jedis.close();
}
string操作
@Test
public void stringTest(){
Jedis jedis = new Jedis("192.168.200.130",6379);
//设置键值对
jedis.set("name","yellowstar");
//获取指定key的value值
System.out.println(jedis.get("name"));
jedis.close();
}
list操作
@Test
public void listTest(){
Jedis jedis = new Jedis("192.168.200.130",6379);
jedis.lpush("names","mary","jack","tom","jerry");
List<String> names = jedis.lrange("names", 0L, -1L);
names.forEach(System.out::println);
jedis.close();
}
set操作
@Test
public void setTest(){
Jedis jedis = new Jedis("192.168.200.130",6379);
jedis.sadd("users","make","wede","james");
Set<String> users = jedis.smembers("users");
users.forEach(System.out::println);
jedis.close();
}
hash操作
@Test
public void hashTest(){
Jedis jedis = new Jedis("192.168.200.130",6379);
HashMap<String, String> map = new HashMap<>();
map.put("id","1");
map.put("name","zhangsan");
map.put("age","18");
jedis.hmset("students",map);
List<String> hmget = jedis.hmget("students", "id", "name", "age");
hmget.forEach(System.out::println);
jedis.close();
}
zset操作
@Test
public void zsetTest(){
Jedis jedis = new Jedis("192.168.200.130",6379);
jedis.zadd("top",100L,"java");
jedis.zadd("top",200L,"c++");
jedis.zadd("top",300L,"python");
List<String> top = jedis.zrange("top", 0L, -1L);
top.forEach(System.out::println);
jedis.close();
}
题目:完成一个手机验证码的功能
1、输入手机号,点击发送后随机生成6位数字码,2分钟内有效
2、输入验证码,点击验证,返回成功或失败
3、每个手机号每天只能发送三次验证码
分析问题
实现
public class JedisDemo {
public static void main(String[] args) {
saveCode("12345678901");
// verifyCode("12345678901","503891");
}
//验证
private static void verifyCode(String phone, String code){
Jedis jedis = new Jedis("192.168.200.130",6379);
String key = "phone" + phone + ":code";
String s = jedis.get(key);
if (code.equals(s)){
System.out.println("成功");
}else {
System.out.println("失败");
}
jedis.close();
}
//输入手机号获取验证码,并保存
private static void saveCode(String phone){
Jedis jedis = new Jedis("192.168.200.130",6379);
// count的key
String countKey = "phone" + phone + ":count";
// code的key
String codeKey = "phone" + phone + ":code";
if (jedis.get(countKey) == null){
jedis.setex(countKey,24*60*60,"1");
}else if (Integer.parseInt(jedis.get(countKey)) < 3){
jedis.incr(countKey);
}else {
System.out.println("每天输入次数不超过三次");
jedis.close();
return;
}
jedis.setex(codeKey,120L,getCode());
jedis.close();
}
//生成随机6位数字验证码
private static String getCode(){
Random random = new Random();
StringBuilder code = new StringBuilder();
for (int i = 0;i<6;i++){
code.append(random.nextInt(10));
}
return code.toString();
}
}
创建spring boot项目
自行创建
导入相关依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-pool2artifactId>
<version>2.11.1version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.79version>
dependency>
编写redisconfig配置类
@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;
}
}
编写controller测试
@RestController
@RequestMapping("/redisTest")
public class RedisController {
@Autowired
RedisTemplate redisTemplate;
@GetMapping
public String getRedis(){
redisTemplate.opsForValue().set("myname","yellowstar");
String myname = (String) redisTemplate.opsForValue().get("myname");
return myname;
}
}