一、通过jedis连接数据库
1.首先导入依赖
<!-- https://mvnrepository.com/artifact/redis.clients/jedis --><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>5.1.0</version></dependency>
2。写出主机号和端口
package com.easy;import redis.clients.jedis.Jedis;import java.util.Set;public class EasyRedisA {public static void main(String[] args) {//通过jedis连接数据库Jedis jedis=new Jedis("127.0.0.1",6379);System.out.println("连接成功");String result=jedis.ping();System.out.println("ping的结果是"+result);result=jedis.set("easyname","何容与");System.out.println("set结果是 "+result);//获取所有的keySet<String> keys=jedis.keys("*");//打印每一个keyfor(String key:keys){System.out.println(key);}jedis.close();}
}
二、SpringBoot整合
1.导入依赖
2.yml配置
3.定义实体类
package org.example.bean;import java.io.Serializable;public class Student implements Serializable {private static final long serialVersionUID=1;private int id;private String name;private int score;private String sex;public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getScore() {return score;}public void setScore(int score) {this.score = score;}@Overridepublic String toString() {return "Student{" +"id=" + id +", name='" + name + '\'' +", score=" + score +'}';}
}
4.控制类
package org.example.Controller;import org.example.bean.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;@RestController
public class EasyRedisController {// @Autowired
// //byType
// @Resource
// //byName@AutowiredRedisTemplate redisTemplate;@RequestMapping("addname")public String addString(){redisTemplate.opsForValue().set("name","xxc");return "ok";}@RequestMapping("getname")public String getStr(){Object obj= redisTemplate.opsForValue().get("name");return obj.toString();}@RequestMapping("addobj")public String addObj(){Student student=new Student();student.setId(1);student.setName("何容与");student.setScore(99);redisTemplate.opsForValue().set("student",student);return "ok";}@RequestMapping("getobj")public Student getObj(){Object obj=redisTemplate.opsForValue().get("student");return (Student)obj;}
}
通过反序列化获得Student对象,要确保Student类能被反序列化。