Java中的使用及连接Redis数据库(附源码)
引言:
本文主要分享了redis如何在idea中部署,运行;模拟加入redis的操作;
目录结构
1. 在idea中搭建redis
1.1 创建项目
新建含有web的springboot项目;
搭建项目参考:springboot超详细笔记:https://blog.csdn.net/weixin_42601136/article/details/108396511
1.2 添加依赖(不够手动添加)
<dependencies> <!-- 1、 jedis--> <dependency> <groupid>redis.clients</groupid> <artifactid>jedis</artifactid> <version>2.9.0</version> </dependency> <!-- 2、 junit测试--> <dependency> <groupid>junit</groupid> <artifactid>junit</artifactid> <version>4.12</version> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-jdbc</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-thymeleaf</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency> <dependency> <groupid>org.mybatis.spring.boot</groupid> <artifactid>mybatis-spring-boot-starter</artifactid> <version>2.1.2</version> </dependency> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <scope>runtime</scope> </dependency> <dependency> <groupid>org.projectlombok</groupid> <artifactid>lombok</artifactid> <optional>true</optional> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-test</artifactid> <scope>test</scope> </dependency> </dependencies>
1.3 测试环境是否搭建成功
@test public void test0() { //连接redis jedis jedis = new jedis("127.0.0.1", 6379); //获取kak string kaka = jedis.get("kak"); log.info(kaka); //创建datex string datex = jedis.set("datex", new date().tostring()); //获取datex string datex1 = jedis.get("datex"); log.info(datex1); //关闭资源 jedis.close(); }
1.4 利用json存储数据
@test public void test1() { jedispool pool = new jedispool("127.0.0.1", 6379); jedis jedis = pool.getresource(); student student = new student(1001, "kak", "man", "20"); string key = "student"; string field = "1001"; string s = jsonutils.objecttojson(student); string value = s; jedis.hset(key, field, value); string hget = jedis.hget(key, field); log.info(hget); jedis.close(); }
1.5 以byte的形式存储对象
@test public void test02() { //连接redis jedis jedis = new jedis("127.0.0.1", 6379); string key = "student"; student value = new student(1002, "taotao", "woman", "20"); //将key和value转换为byte[] byte[] bytekey = serializationutils.serialize(key); byte[] bytevalue = serializationutils.serialize(value); //将key和value存储到redis中 jedis.set(bytekey, bytevalue); //获取value值 byte[] bytes = jedis.get(bytekey); //bytes反序列化为student对象 student stu = (student) serializationutils.deserialize(bytes); system.out.println(stu); jedis.close(); }
1.6 加入连接池的操作
使用连接池操作,可以避免频繁的创建和销毁连接对象的消耗资源
@test public void test3(){ //创建连接池 genericobjectpoolconfig poolconfig = new genericobjectpoolconfig(); poolconfig.setmaxtotal(100);//连接池中的最大活跃数 poolconfig.setmaxidle(10);//最大空闲数 poolconfig.setminidle(5);//最小空闲数 poolconfig.setmaxwaitmillis(3000);//连接池空了,3000毫秒后没有获取jedis对象,超时 //创建连接池 jedispool pool = new jedispool(poolconfig,"127.0.0.1",6379); //通过连接池获取jedis对象 jedis resource = pool.getresource(); //获取上面添加的datex string value = resource.get("datex"); log.info(value); resource.close(); }
1.7 管道操作
redis的管道操作,执行一个命令需要先发送请求到redis,需要经历网络延迟,redis还需给客户端一个响应;如果需要一次操作多个命令,可以通过管道,将命令放到客户端的一个pipeline中,之后一次将命令发送到服务端,服务端一次性返回到客户端;
@test public void test3(){ //创建连接池 genericobjectpoolconfig poolconfig = new genericobjectpoolconfig(); poolconfig.setmaxtotal(100);//连接池中的最大活跃数 poolconfig.setmaxidle(10);//最大空闲数 poolconfig.setminidle(5);//最小空闲数 poolconfig.setmaxwaitmillis(3000);//连接池空了,3000毫秒后没有获取jedis对象,超时 //创建连接池 jedispool pool = new jedispool(poolconfig,"127.0.0.1",6379); //通过连接池获取jedis对象 jedis resource = pool.getresource(); //获取上面添加的datex string value = resource.get("datex"); log.info(value); resource.close(); }
2. 从数据中查询数据
场景:
将数据存入redis中,避免访问量过大,造成数据库奔溃;
2.1 生成实体类
@test public void test3(){ //创建连接池 genericobjectpoolconfig poolconfig = new genericobjectpoolconfig(); poolconfig.setmaxtotal(100);//连接池中的最大活跃数 poolconfig.setmaxidle(10);//最大空闲数 poolconfig.setminidle(5);//最小空闲数 poolconfig.setmaxwaitmillis(3000);//连接池空了,3000毫秒后没有获取jedis对象,超时 //创建连接池 jedispool pool = new jedispool(poolconfig,"127.0.0.1",6379); //通过连接池获取jedis对象 jedis resource = pool.getresource(); //获取上面添加的datex string value = resource.get("datex"); log.info(value); resource.close(); }
2.2 生成实体模板类
package com.sx.kak.po; import java.util.arraylist; import java.util.list; public class studentexample { protected string orderbyclause; protected boolean distinct; protected list<criteria> oredcriteria; public studentexample() { oredcriteria = new arraylist<criteria>(); } public void setorderbyclause(string orderbyclause) { this.orderbyclause = orderbyclause; } public string getorderbyclause() { return orderbyclause; } public void setdistinct(boolean distinct) { this.distinct = distinct; } public boolean isdistinct() { return distinct; } public list<criteria> getoredcriteria() { return oredcriteria; } public void or(criteria criteria) { oredcriteria.add(criteria); } public criteria or() { criteria criteria = createcriteriainternal(); oredcriteria.add(criteria); return criteria; } public criteria createcriteria() { criteria criteria = createcriteriainternal(); if (oredcriteria.size() == 0) { oredcriteria.add(criteria); } return criteria; } protected criteria createcriteriainternal() { criteria criteria = new criteria(); return criteria; } public void clear() { oredcriteria.clear(); orderbyclause = null; distinct = false; } protected abstract static class generatedcriteria { protected list<criterion> criteria; protected generatedcriteria() { super(); criteria = new arraylist<criterion>(); } public boolean isvalid() { return criteria.size() > 0; } public list<criterion> getallcriteria() { return criteria; } public list<criterion> getcriteria() { return criteria; } protected void addcriterion(string condition) { if (condition == null) { throw new runtimeexception("value for condition cannot be null"); } criteria.add(new criterion(condition)); } protected void addcriterion(string condition, object value, string property) { if (value == null) { throw new runtimeexception("value for " + property + " cannot be null"); } criteria.add(new criterion(condition, value)); } protected void addcriterion(string condition, object value1, object value2, string property) { if (value1 == null || value2 == null) { throw new runtimeexception("between values for " + property + " cannot be null"); } criteria.add(new criterion(condition, value1, value2)); } public criteria andidisnull() { addcriterion("id is null"); return (criteria) this; } public criteria andidisnotnull() { addcriterion("id is not null"); return (criteria) this; } public criteria andidequalto(integer value) { addcriterion("id =", value, "id"); return (criteria) this; } public criteria andidnotequalto(integer value) { addcriterion("id <>", value, "id"); return (criteria) this; } public criteria andidgreaterthan(integer value) { addcriterion("id >", value, "id"); return (criteria) this; } public criteria andidgreaterthanorequalto(integer value) { addcriterion("id >=", value, "id"); return (criteria) this; } public criteria andidlessthan(integer value) { addcriterion("id <", value, "id"); return (criteria) this; } public criteria andidlessthanorequalto(integer value) { addcriterion("id <=", value, "id"); return (criteria) this; } public criteria andidin(list<integer> values) { addcriterion("id in", values, "id"); return (criteria) this; } public criteria andidnotin(list<integer> values) { addcriterion("id not in", values, "id"); return (criteria) this; } public criteria andidbetween(integer value1, integer value2) { addcriterion("id between", value1, value2, "id"); return (criteria) this; } public criteria andidnotbetween(integer value1, integer value2) { addcriterion("id not between", value1, value2, "id"); return (criteria) this; } public criteria andnameisnull() { addcriterion("name is null"); return (criteria) this; } public criteria andnameisnotnull() { addcriterion("name is not null"); return (criteria) this; } public criteria andnameequalto(string value) { addcriterion("name =", value, "name"); return (criteria) this; } public criteria andnamenotequalto(string value) { addcriterion("name <>", value, "name"); return (criteria) this; } public criteria andnamegreaterthan(string value) { addcriterion("name >", value, "name"); return (criteria) this; } public criteria andnamegreaterthanorequalto(string value) { addcriterion("name >=", value, "name"); return (criteria) this; } public criteria andnamelessthan(string value) { addcriterion("name <", value, "name"); return (criteria) this; } public criteria andnamelessthanorequalto(string value) { addcriterion("name <=", value, "name"); return (criteria) this; } public criteria andnamelike(string value) { addcriterion("name like", value, "name"); return (criteria) this; } public criteria andnamenotlike(string value) { addcriterion("name not like", value, "name"); return (criteria) this; } public criteria andnamein(list<string> values) { addcriterion("name in", values, "name"); return (criteria) this; } public criteria andnamenotin(list<string> values) { addcriterion("name not in", values, "name"); return (criteria) this; } public criteria andnamebetween(string value1, string value2) { addcriterion("name between", value1, value2, "name"); return (criteria) this; } public criteria andnamenotbetween(string value1, string value2) { addcriterion("name not between", value1, value2, "name"); return (criteria) this; } public criteria andsexisnull() { addcriterion("sex is null"); return (criteria) this; } public criteria andsexisnotnull() { addcriterion("sex is not null"); return (criteria) this; } public criteria andsexequalto(string value) { addcriterion("sex =", value, "sex"); return (criteria) this; } public criteria andsexnotequalto(string value) { addcriterion("sex <>", value, "sex"); return (criteria) this; } public criteria andsexgreaterthan(string value) { addcriterion("sex >", value, "sex"); return (criteria) this; } public criteria andsexgreaterthanorequalto(string value) { addcriterion("sex >=", value, "sex"); return (criteria) this; } public criteria andsexlessthan(string value) { addcriterion("sex <", value, "sex"); return (criteria) this; } public criteria andsexlessthanorequalto(string value) { addcriterion("sex <=", value, "sex"); return (criteria) this; } public criteria andsexlike(string value) { addcriterion("sex like", value, "sex"); return (criteria) this; } public criteria andsexnotlike(string value) { addcriterion("sex not like", value, "sex"); return (criteria) this; } public criteria andsexin(list<string> values) { addcriterion("sex in", values, "sex"); return (criteria) this; } public criteria andsexnotin(list<string> values) { addcriterion("sex not in", values, "sex"); return (criteria) this; } public criteria andsexbetween(string value1, string value2) { addcriterion("sex between", value1, value2, "sex"); return (criteria) this; } public criteria andsexnotbetween(string value1, string value2) { addcriterion("sex not between", value1, value2, "sex"); return (criteria) this; } public criteria andageisnull() { addcriterion("age is null"); return (criteria) this; } public criteria andageisnotnull() { addcriterion("age is not null"); return (criteria) this; } public criteria andageequalto(string value) { addcriterion("age =", value, "age"); return (criteria) this; } public criteria andagenotequalto(string value) { addcriterion("age <>", value, "age"); return (criteria) this; } public criteria andagegreaterthan(string value) { addcriterion("age >", value, "age"); return (criteria) this; } public criteria andagegreaterthanorequalto(string value) { addcriterion("age >=", value, "age"); return (criteria) this; } public criteria andagelessthan(string value) { addcriterion("age <", value, "age"); return (criteria) this; } public criteria andagelessthanorequalto(string value) { addcriterion("age <=", value, "age"); return (criteria) this; } public criteria andagelike(string value) { addcriterion("age like", value, "age"); return (criteria) this; } public criteria andagenotlike(string value) { addcriterion("age not like", value, "age"); return (criteria) this; } public criteria andagein(list<string> values) { addcriterion("age in", values, "age"); return (criteria) this; } public criteria andagenotin(list<string> values) { addcriterion("age not in", values, "age"); return (criteria) this; } public criteria andagebetween(string value1, string value2) { addcriterion("age between", value1, value2, "age"); return (criteria) this; } public criteria andagenotbetween(string value1, string value2) { addcriterion("age not between", value1, value2, "age"); return (criteria) this; } } public static class criteria extends generatedcriteria { protected criteria() { super(); } } public static class criterion { private string condition; private object value; private object secondvalue; private boolean novalue; private boolean singlevalue; private boolean betweenvalue; private boolean listvalue; private string typehandler; public string getcondition() { return condition; } public object getvalue() { return value; } public object getsecondvalue() { return secondvalue; } public boolean isnovalue() { return novalue; } public boolean issinglevalue() { return singlevalue; } public boolean isbetweenvalue() { return betweenvalue; } public boolean islistvalue() { return listvalue; } public string gettypehandler() { return typehandler; } protected criterion(string condition) { super(); this.condition = condition; this.typehandler = null; this.novalue = true; } protected criterion(string condition, object value, string typehandler) { super(); this.condition = condition; this.value = value; this.typehandler = typehandler; if (value instanceof list<?>) { this.listvalue = true; } else { this.singlevalue = true; } } protected criterion(string condition, object value) { this(condition, value, null); } protected criterion(string condition, object value, object secondvalue, string typehandler) { super(); this.condition = condition; this.value = value; this.secondvalue = secondvalue; this.typehandler = typehandler; this.betweenvalue = true; } protected criterion(string condition, object value, object secondvalue) { this(condition, value, secondvalue, null); } } }
2.3 生成studentmapper.java
package com.sx.kak.po; import java.util.arraylist; import java.util.list; public class studentexample { protected string orderbyclause; protected boolean distinct; protected list<criteria> oredcriteria; public studentexample() { oredcriteria = new arraylist<criteria>(); } public void setorderbyclause(string orderbyclause) { this.orderbyclause = orderbyclause; } public string getorderbyclause() { return orderbyclause; } public void setdistinct(boolean distinct) { this.distinct = distinct; } public boolean isdistinct() { return distinct; } public list<criteria> getoredcriteria() { return oredcriteria; } public void or(criteria criteria) { oredcriteria.add(criteria); } public criteria or() { criteria criteria = createcriteriainternal(); oredcriteria.add(criteria); return criteria; } public criteria createcriteria() { criteria criteria = createcriteriainternal(); if (oredcriteria.size() == 0) { oredcriteria.add(criteria); } return criteria; } protected criteria createcriteriainternal() { criteria criteria = new criteria(); return criteria; } public void clear() { oredcriteria.clear(); orderbyclause = null; distinct = false; } protected abstract static class generatedcriteria { protected list<criterion> criteria; protected generatedcriteria() { super(); criteria = new arraylist<criterion>(); } public boolean isvalid() { return criteria.size() > 0; } public list<criterion> getallcriteria() { return criteria; } public list<criterion> getcriteria() { return criteria; } protected void addcriterion(string condition) { if (condition == null) { throw new runtimeexception("value for condition cannot be null"); } criteria.add(new criterion(condition)); } protected void addcriterion(string condition, object value, string property) { if (value == null) { throw new runtimeexception("value for " + property + " cannot be null"); } criteria.add(new criterion(condition, value)); } protected void addcriterion(string condition, object value1, object value2, string property) { if (value1 == null || value2 == null) { throw new runtimeexception("between values for " + property + " cannot be null"); } criteria.add(new criterion(condition, value1, value2)); } public criteria andidisnull() { addcriterion("id is null"); return (criteria) this; } public criteria andidisnotnull() { addcriterion("id is not null"); return (criteria) this; } public criteria andidequalto(integer value) { addcriterion("id =", value, "id"); return (criteria) this; } public criteria andidnotequalto(integer value) { addcriterion("id <>", value, "id"); return (criteria) this; } public criteria andidgreaterthan(integer value) { addcriterion("id >", value, "id"); return (criteria) this; } public criteria andidgreaterthanorequalto(integer value) { addcriterion("id >=", value, "id"); return (criteria) this; } public criteria andidlessthan(integer value) { addcriterion("id <", value, "id"); return (criteria) this; } public criteria andidlessthanorequalto(integer value) { addcriterion("id <=", value, "id"); return (criteria) this; } public criteria andidin(list<integer> values) { addcriterion("id in", values, "id"); return (criteria) this; } public criteria andidnotin(list<integer> values) { addcriterion("id not in", values, "id"); return (criteria) this; } public criteria andidbetween(integer value1, integer value2) { addcriterion("id between", value1, value2, "id"); return (criteria) this; } public criteria andidnotbetween(integer value1, integer value2) { addcriterion("id not between", value1, value2, "id"); return (criteria) this; } public criteria andnameisnull() { addcriterion("name is null"); return (criteria) this; } public criteria andnameisnotnull() { addcriterion("name is not null"); return (criteria) this; } public criteria andnameequalto(string value) { addcriterion("name =", value, "name"); return (criteria) this; } public criteria andnamenotequalto(string value) { addcriterion("name <>", value, "name"); return (criteria) this; } public criteria andnamegreaterthan(string value) { addcriterion("name >", value, "name"); return (criteria) this; } public criteria andnamegreaterthanorequalto(string value) { addcriterion("name >=", value, "name"); return (criteria) this; } public criteria andnamelessthan(string value) { addcriterion("name <", value, "name"); return (criteria) this; } public criteria andnamelessthanorequalto(string value) { addcriterion("name <=", value, "name"); return (criteria) this; } public criteria andnamelike(string value) { addcriterion("name like", value, "name"); return (criteria) this; } public criteria andnamenotlike(string value) { addcriterion("name not like", value, "name"); return (criteria) this; } public criteria andnamein(list<string> values) { addcriterion("name in", values, "name"); return (criteria) this; } public criteria andnamenotin(list<string> values) { addcriterion("name not in", values, "name"); return (criteria) this; } public criteria andnamebetween(string value1, string value2) { addcriterion("name between", value1, value2, "name"); return (criteria) this; } public criteria andnamenotbetween(string value1, string value2) { addcriterion("name not between", value1, value2, "name"); return (criteria) this; } public criteria andsexisnull() { addcriterion("sex is null"); return (criteria) this; } public criteria andsexisnotnull() { addcriterion("sex is not null"); return (criteria) this; } public criteria andsexequalto(string value) { addcriterion("sex =", value, "sex"); return (criteria) this; } public criteria andsexnotequalto(string value) { addcriterion("sex <>", value, "sex"); return (criteria) this; } public criteria andsexgreaterthan(string value) { addcriterion("sex >", value, "sex"); return (criteria) this; } public criteria andsexgreaterthanorequalto(string value) { addcriterion("sex >=", value, "sex"); return (criteria) this; } public criteria andsexlessthan(string value) { addcriterion("sex <", value, "sex"); return (criteria) this; } public criteria andsexlessthanorequalto(string value) { addcriterion("sex <=", value, "sex"); return (criteria) this; } public criteria andsexlike(string value) { addcriterion("sex like", value, "sex"); return (criteria) this; } public criteria andsexnotlike(string value) { addcriterion("sex not like", value, "sex"); return (criteria) this; } public criteria andsexin(list<string> values) { addcriterion("sex in", values, "sex"); return (criteria) this; } public criteria andsexnotin(list<string> values) { addcriterion("sex not in", values, "sex"); return (criteria) this; } public criteria andsexbetween(string value1, string value2) { addcriterion("sex between", value1, value2, "sex"); return (criteria) this; } public criteria andsexnotbetween(string value1, string value2) { addcriterion("sex not between", value1, value2, "sex"); return (criteria) this; } public criteria andageisnull() { addcriterion("age is null"); return (criteria) this; } public criteria andageisnotnull() { addcriterion("age is not null"); return (criteria) this; } public criteria andageequalto(string value) { addcriterion("age =", value, "age"); return (criteria) this; } public criteria andagenotequalto(string value) { addcriterion("age <>", value, "age"); return (criteria) this; } public criteria andagegreaterthan(string value) { addcriterion("age >", value, "age"); return (criteria) this; } public criteria andagegreaterthanorequalto(string value) { addcriterion("age >=", value, "age"); return (criteria) this; } public criteria andagelessthan(string value) { addcriterion("age <", value, "age"); return (criteria) this; } public criteria andagelessthanorequalto(string value) { addcriterion("age <=", value, "age"); return (criteria) this; } public criteria andagelike(string value) { addcriterion("age like", value, "age"); return (criteria) this; } public criteria andagenotlike(string value) { addcriterion("age not like", value, "age"); return (criteria) this; } public criteria andagein(list<string> values) { addcriterion("age in", values, "age"); return (criteria) this; } public criteria andagenotin(list<string> values) { addcriterion("age not in", values, "age"); return (criteria) this; } public criteria andagebetween(string value1, string value2) { addcriterion("age between", value1, value2, "age"); return (criteria) this; } public criteria andagenotbetween(string value1, string value2) { addcriterion("age not between", value1, value2, "age"); return (criteria) this; } } public static class criteria extends generatedcriteria { protected criteria() { super(); } } public static class criterion { private string condition; private object value; private object secondvalue; private boolean novalue; private boolean singlevalue; private boolean betweenvalue; private boolean listvalue; private string typehandler; public string getcondition() { return condition; } public object getvalue() { return value; } public object getsecondvalue() { return secondvalue; } public boolean isnovalue() { return novalue; } public boolean issinglevalue() { return singlevalue; } public boolean isbetweenvalue() { return betweenvalue; } public boolean islistvalue() { return listvalue; } public string gettypehandler() { return typehandler; } protected criterion(string condition) { super(); this.condition = condition; this.typehandler = null; this.novalue = true; } protected criterion(string condition, object value, string typehandler) { super(); this.condition = condition; this.value = value; this.typehandler = typehandler; if (value instanceof list<?>) { this.listvalue = true; } else { this.singlevalue = true; } } protected criterion(string condition, object value) { this(condition, value, null); } protected criterion(string condition, object value, object secondvalue, string typehandler) { super(); this.condition = condition; this.value = value; this.secondvalue = secondvalue; this.typehandler = typehandler; this.betweenvalue = true; } protected criterion(string condition, object value, object secondvalue) { this(condition, value, secondvalue, null); } } }
2.4 生成studentmapper.xml
<?xml version="1.0" encoding="utf-8" ?> <!doctype mapper public "-//mybatis.org//dtd mapper 3.0//en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.sx.kak.mapper.studentmapper" > <resultmap id="baseresultmap" type="com.sx.kak.po.student" > <id column="id" property="id" jdbctype="integer" /> <result column="name" property="name" jdbctype="varchar" /> <result column="sex" property="sex" jdbctype="varchar" /> <result column="age" property="age" jdbctype="varchar" /> </resultmap> <sql id="example_where_clause" > <where > <foreach collection="oredcriteria" item="criteria" separator="or" > <if test="criteria.valid" > <trim prefix="(" suffix=")" prefixoverrides="and" > <foreach collection="criteria.criteria" item="criterion" > <choose > <when test="criterion.novalue" > and ${criterion.condition} </when> <when test="criterion.singlevalue" > and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenvalue" > and ${criterion.condition} #{criterion.value} and #{criterion.secondvalue} </when> <when test="criterion.listvalue" > and ${criterion.condition} <foreach collection="criterion.value" item="listitem" open="(" close=")" separator="," > #{listitem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="update_by_example_where_clause" > <where > <foreach collection="example.oredcriteria" item="criteria" separator="or" > <if test="criteria.valid" > <trim prefix="(" suffix=")" prefixoverrides="and" > <foreach collection="criteria.criteria" item="criterion" > <choose > <when test="criterion.novalue" > and ${criterion.condition} </when> <when test="criterion.singlevalue" > and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenvalue" > and ${criterion.condition} #{criterion.value} and #{criterion.secondvalue} </when> <when test="criterion.listvalue" > and ${criterion.condition} <foreach collection="criterion.value" item="listitem" open="(" close=")" separator="," > #{listitem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="base_column_list" > id, name, sex, age </sql> <select id="selectbyexample" resultmap="baseresultmap" parametertype="com.sx.kak.po.studentexample" > select <if test="distinct" > distinct </if> <include refid="base_column_list" /> from student <if test="_parameter != null" > <include refid="example_where_clause" /> </if> <if test="orderbyclause != null" > order by ${orderbyclause} </if> </select> <select id="selectbyprimarykey" resultmap="baseresultmap" parametertype="java.lang.integer" > select <include refid="base_column_list" /> from student where id = #{id,jdbctype=integer} </select> <delete id="deletebyprimarykey" parametertype="java.lang.integer" > delete from student where id = #{id,jdbctype=integer} </delete> <delete id="deletebyexample" parametertype="com.sx.kak.po.studentexample" > delete from student <if test="_parameter != null" > <include refid="example_where_clause" /> </if> </delete> <insert id="insert" parametertype="com.sx.kak.po.student" > insert into student (id, name, sex, age) values (#{id,jdbctype=integer}, #{name,jdbctype=varchar}, #{sex,jdbctype=varchar}, #{age,jdbctype=varchar}) </insert> <insert id="insertselective" parametertype="com.sx.kak.po.student" > insert into student <trim prefix="(" suffix=")" suffixoverrides="," > <if test="id != null" > id, </if> <if test="name != null" > name, </if> <if test="sex != null" > sex, </if> <if test="age != null" > age, </if> </trim> <trim prefix="values (" suffix=")" suffixoverrides="," > <if test="id != null" > #{id,jdbctype=integer}, </if> <if test="name != null" > #{name,jdbctype=varchar}, </if> <if test="sex != null" > #{sex,jdbctype=varchar}, </if> <if test="age != null" > #{age,jdbctype=varchar}, </if> </trim> </insert> <select id="countbyexample" parametertype="com.sx.kak.po.studentexample" resulttype="java.lang.integer" > select count(*) from student <if test="_parameter != null" > <include refid="example_where_clause" /> </if> </select> <update id="updatebyexampleselective" parametertype="map" > update student <set > <if test="record.id != null" > id = #{record.id,jdbctype=integer}, </if> <if test="record.name != null" > name = #{record.name,jdbctype=varchar}, </if> <if test="record.sex != null" > sex = #{record.sex,jdbctype=varchar}, </if> <if test="record.age != null" > age = #{record.age,jdbctype=varchar}, </if> </set> <if test="_parameter != null" > <include refid="update_by_example_where_clause" /> </if> </update> <update id="updatebyexample" parametertype="map" > update student set id = #{record.id,jdbctype=integer}, name = #{record.name,jdbctype=varchar}, sex = #{record.sex,jdbctype=varchar}, age = #{record.age,jdbctype=varchar} <if test="_parameter != null" > <include refid="update_by_example_where_clause" /> </if> </update> <update id="updatebyprimarykeyselective" parametertype="com.sx.kak.po.student" > update student <set > <if test="name != null" > name = #{name,jdbctype=varchar}, </if> <if test="sex != null" > sex = #{sex,jdbctype=varchar}, </if> <if test="age != null" > age = #{age,jdbctype=varchar}, </if> </set> where id = #{id,jdbctype=integer} </update> <update id="updatebyprimarykey" parametertype="com.sx.kak.po.student" > update student set name = #{name,jdbctype=varchar}, sex = #{sex,jdbctype=varchar}, age = #{age,jdbctype=varchar} where id = #{id,jdbctype=integer} </update> </mapper>
2.5 编写application.yml
server: port: 8080 spring: datasource: driver-class-name: com.mysql.cj.jdbc.driver url: jdbc:mysql://localhost:3306/db0711?characterencoding=utf8&servertimezone=utc username: root password: root mybatis: type-aliases-package: po mapper-locations: classpath:mapping/*.xml
2.6 编写jsonutils工具类
package com.sx.kak.utils; import java.util.list; import com.fasterxml.jackson.core.jsonprocessingexception; import com.fasterxml.jackson.databind.javatype; import com.fasterxml.jackson.databind.objectmapper; public class jsonutils { // 定义jackson对象 private static final objectmapper mapper = new objectmapper(); /** * 将对象转换成json字符串。 * <p>title: pojotojson</p> * <p>description: </p> * @param data * @return */ public static string objecttojson(object data) { try { string string = mapper.writevalueasstring(data); return string; } catch (jsonprocessingexception e) { e.printstacktrace(); } return null; } /** * 将json结果集转化为对象 * * @param jsondata json数据 * @param clazz 对象中的object类型 * @return */ public static <t> t jsontopojo(string jsondata, class<t> beantype) { try { t t = mapper.readvalue(jsondata, beantype); return t; } catch (exception e) { e.printstacktrace(); } return null; } /** * 将json数据转换成pojo对象list * <p>title: jsontolist</p> * <p>description: </p> * @param jsondata * @param beantype * @return */ public static <t>list<t> jsontolist(string jsondata, class<t> beantype) { javatype javatype = mapper.gettypefactory().constructparametrictype(list.class, beantype); try { list<t> list = mapper.readvalue(jsondata, javatype); return list; } catch (exception e) { e.printstacktrace(); } return null; } }
2.7 编写redisutils工具类
package com.sx.kak.utils; import java.util.list; import com.fasterxml.jackson.core.jsonprocessingexception; import com.fasterxml.jackson.databind.javatype; import com.fasterxml.jackson.databind.objectmapper; public class jsonutils { // 定义jackson对象 private static final objectmapper mapper = new objectmapper(); /** * 将对象转换成json字符串。 * <p>title: pojotojson</p> * <p>description: </p> * @param data * @return */ public static string objecttojson(object data) { try { string string = mapper.writevalueasstring(data); return string; } catch (jsonprocessingexception e) { e.printstacktrace(); } return null; } /** * 将json结果集转化为对象 * * @param jsondata json数据 * @param clazz 对象中的object类型 * @return */ public static <t> t jsontopojo(string jsondata, class<t> beantype) { try { t t = mapper.readvalue(jsondata, beantype); return t; } catch (exception e) { e.printstacktrace(); } return null; } /** * 将json数据转换成pojo对象list * <p>title: jsontolist</p> * <p>description: </p> * @param jsondata * @param beantype * @return */ public static <t>list<t> jsontolist(string jsondata, class<t> beantype) { javatype javatype = mapper.gettypefactory().constructparametrictype(list.class, beantype); try { list<t> list = mapper.readvalue(jsondata, javatype); return list; } catch (exception e) { e.printstacktrace(); } return null; } }
2.8 编写redisutils工具类的实现类
package com.sx.kak.utils; import redis.clients.jedis.jedis; /** * created by kak on 2020/9/17. */ public class singletonredisutil implements redisutils{ private jedis jedis; public singletonredisutil(jedis jedis){ this.jedis = jedis; } @override public void hset(string key, string filed, string value) { jedis.hset(key, filed, value); } @override public string hget(string key, string field) { return jedis.hget(key, field); } }
2.9 配置初始化文件
package com.sx.kak.config; import com.sx.kak.utils.singletonredisutil; import org.springframework.beans.factory.annotation.qualifier; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import redis.clients.jedis.jedis; /** * created by kak on 2020/9/17. */ @configuration public class redisconfig { @bean public singletonredisutil singletonredisutil(@qualifier("jedis") jedis jedis){ singletonredisutil singletonredisutil = new singletonredisutil(jedis); return singletonredisutil; } @bean(name = "jedis") public jedis getjedis(){ jedis jedis = new jedis("127.0.0.1",6379); return jedis; } }
2.10 配置studentservice.java
package com.sx.kak.service; import com.sx.kak.po.student; import java.util.list; /** * created by kak on 2020/9/17. */ public interface studentservice { public list<student> findallstudent(); }
2.11 配置studentserviceimpl.java
package com.sx.kak.service.serviceimpl; import com.sx.kak.mapper.studentmapper; import com.sx.kak.po.student; import com.sx.kak.po.studentexample; import com.sx.kak.service.studentservice; import com.sx.kak.utils.jsonutils; import com.sx.kak.utils.singletonredisutil; import lombok.extern.slf4j.slf4j; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.service; import java.util.list; /** * created by kak on 2020/9/17. */ @service @slf4j public class studentserviceimpl implements studentservice { @autowired(required = false) private studentmapper studentmapper; //注入自定义的redis工具 @autowired private singletonredisutil redisutil; @override public list<student> findallstudent() { //获取redis中存出的json字符串 string student = redisutil.hget("student", "0"); if(student!=null){ log.info("get student from redis"); //json对象,封装的对象类型 list<student> students = jsonutils.jsontolist(student, student.class); return students; } //创建查询模板对象 studentexample studentexample = new studentexample(); list<student> students = studentmapper.selectbyexample(studentexample); log.info("get student from db"); try{ //将查询的集合转化为json字符串 string s = jsonutils.objecttojson(students); //放入redis中 redisutil.hset("student","0",s); log.info("set data to redis"); }catch (exception ex){ log.info(ex.getmessage()); } return students; } }
2.12 编写全查展示页面
<!doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"/> <title>学生全查页面</title> </head> <body> <div id="findall"> <table> <tr> <th>id</th> <th>name</th> <th>sex</th> <th>age</th> <th>action</th> </tr> <tr th:each="s:${students}"> <td th:text="${s.id}"></td> <td th:text="${s.name}"></td> <td th:text="${s.sex}"></td> <td th:text="${s.age}"></td> </tr> </table> </div> </body> </html>
2.13 编写studentcontroller
package com.sx.kak.controller; import com.sx.kak.po.student; import com.sx.kak.service.studentservice; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.controller; import org.springframework.ui.model; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.restcontroller; import java.util.list; /** * created by kak on 2020/9/17. */ @controller public class studentcontroller { @autowired(required = false) private studentservice studentservice; @requestmapping("/findstudent") public string findallstu(model model){ list<student> allstudent = studentservice.findallstudent(); model.addattribute("students",allstudent); return "showallstudent"; } }
3. 结果
从打印出的日志可以看出,第一次访问是从数据库得到数据,然后存入redis中
第二次直接从redis中获取
到此这篇关于java中的使用及连接redis数据库(附源码)的文章就介绍到这了,更多相关java 使用及连接redis内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
推荐阅读
-
java连接redis是数据库(redis在java项目中的使用)
-
java连接redis是数据库(redis在java项目中的使用)
-
使用JAVA中的动态代理实现数据库连接池 JavaSQLJDBC应用服务器互联网
-
使用ODBC数据库管理Serv-U的FTP用户及相关ASP编程[附源码示例下载]
-
Java中的使用及连接Redis数据库(附源码)
-
java中Future与FutureTask之间的关系及使用(附代码)
-
使用ODBC数据库管理Serv-U的FTP用户及相关ASP编程[附源码示例下载]
-
java中Future与FutureTask之间的关系及使用(附代码)
-
java中JDBC连接oracle数据库的方法介绍(附代码)
-
Java中的使用及连接Redis数据库(附源码)