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内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • java基于jedisLock—redis分布式锁实现示例代码

    分布式锁是啥? 单机锁的概念:我们正常跑的单机项目(也就是在tomcat下跑一个项目不配置集群)想要在高并发的时候加锁很容易就可以搞定,java提供了很多的机制例如:synchronized.volatile.ReentrantLock等锁的机制. 为啥需要分布式锁:当我们的项目比较庞大的时候,单机版的项目已经不能满足吞吐量的需求了,需要对项目做负载均衡,有可能还需要对项目进行解耦拆分成不同的服务,那么肯定是做成分布式的项目,分布式的项目因为是不同的程序控制,所以使用java提供的锁并不能完全保

  • Java中使用Jedis操作Redis的示例代码

    使用Java操作Redis需要jedis-2.1.0.jar,下载地址:jedis-2.1.0.jar 如果需要使用Redis连接池的话,还需commons-pool-1.5.4.jar,下载地址:commons-pool-1.5.4.jar package com.test; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.j

  • java遍历读取整个redis数据库实例

    redis提供了灵活的数据查询方式,最牛的就是key的搜索支持正则表达式. jedis.keys("*");表示搜索所有keyjedis.keys("abc*")表示搜索开头为abc的key数据 遍历了key就能遍历到value. 其实就是一个set 复制代码 代码如下: RedisDO rd = new RedisDO();  rd.open();  Set s = rd.jedis.keys("*");  Iterator it = s.it

  • java 连接Redis的小例子

    需要相应API (jedis-2.1.0.jar) 复制代码 代码如下: package com.redis; import redis.clients.jedis.Jedis; public class Client {    public void getCache(String key){        Jedis jedis = new Jedis("127.0.0.1",6379); for (int i = 0; i < 100000; i++){          

  • Java利用Redis实现消息队列的示例代码

    本文介绍了Java利用Redis实现消息队列的示例代码,分享给大家,具体如下: 应用场景 为什么要用redis? 二进制存储.java序列化传输.IO连接数高.连接频繁 一.序列化 这里编写了一个java序列化的工具,主要是将对象转化为byte数组,和根据byte数组反序列化成java对象; 主要是用到了ByteArrayOutputStream和ByteArrayInputStream; 注意:每个需要序列化的对象都要实现Serializable接口; 其代码如下: package Utils

  • redis中使用java脚本实现分布式锁

    redis被大量用在分布式的环境中,自然而然分布式环境下的锁如何解决,立马成为一个问题.例如我们当前的手游项目,服务器端是按业务模块划分服务器的,有应用服,战斗服等,但是这两个vm都有可能同时改变玩家的属性,这如果在同一个vm下面,就很容易加锁,但如果在分布式环境下就没那么容易了,当然利用redis现有的功能也有解决办法,比如redis的脚本. redis在2.6以后的版本中增加了Lua脚本的功能,可以通过eval命令,直接在RedisServer环境中执行Lua脚本,并且可以在Lua脚本中调用

  • redis在java中的使用(实例讲解)

    1.首先下载jar包放到你的工程中 2.练习 package com.jianyuan.redisTest; import java.util.Iterator; import java.util.List; import java.util.Set; import redis.clients.jedis.Jedis; public class RedisTest { public static void main(String[] args) { //连接本地的Redis服务 Jedis je

  • Java自定义注解实现Redis自动缓存的方法

    在实际开发中,可能经常会有这样的需要:从MySQL中查询一条数据(比如用户信息),此时需要将用户信息保存至Redis. 刚开始我们可能会在查询的业务逻辑之后再写一段Redis相关操作的代码,时间长了后发现这部分代码实际上仅仅做了Redis的写入动作,跟业务逻辑没有实质的联系,那么有没有什么方法能让我们省略这些重复劳动呢? 首先想到用AOP,在查询到某些数据这一切入点(Pointcut)完成我们的切面相关处理(也就是写入Redis).那么,如何知道什么地方需要进行缓存呢,也就是什么地方需要用到AO

  • 详解Java如何实现基于Redis的分布式锁

    前言 单JVM内同步好办, 直接用JDK提供的锁就可以了,但是跨进程同步靠这个肯定是不可能的,这种情况下肯定要借助第三方,我这里实现用Redis,当然还有很多其他的实现方式.其实基于Redis实现的原理还算比较简单的,在看代码之前建议大家先去看看原理,看懂了之后看代码应该就容易理解了. 我这里不实现JDK的java.util.concurrent.locks.Lock接口,而是自定义一个,因为JDK的有个newCondition方法我这里暂时没实现.这个Lock提供了5个lock方法的变体,可以

  • 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--> <depend

  • Java中String的JdbcTemplate连接SQLServer数据库的方法

    很久没写文章了,一方面是最近几个月比较忙,没太多时间,另一方面是最近拖延症严重,写文章的想法总是一拖再拖.今天找一个小案例写一下,与懒惰对抗一下. 首先说一下背景,我们在项目中做数据持久化一般都是用mybatis或者hibernate开发框架,进行数据库连接和操作,最近做GIS仿真产品研发,根据需求需要保存三部分数据:1.业务数据,数据量比较小:2.GIS数据,需要用到空间关系:3.物联数据,数据量大,在我们开发自测阶段数据量就可以达到每天百万以上.根据以上数据特点,我们使用了传统的MySQL数

  • java中string.trim()函数的作用实例及源码

    trim()的作用:去掉字符串首尾的空格. public static void main(String arg[]){ String a=" hello world "; String b="hello world"; System.out.println(b.equals(a)); a=a.trim(); //去掉字符串首尾的空格 System.out.println(a.equals(b)); } 执行结果: a: hello world ,false a:h

  • Java实现贪吃蛇大作战小游戏(附源码)

    目录 1.开发环境及游戏展示 1.1 游戏主界面 1.2 移动界面 1.3 奖励界面 1.4 F加速功能界面 1.5 死亡界面 2.需求分析 3.系统设计 3.1 系统总体功能设计 3.2 系统总体流程设计 4.功能设计 4.1 贪吃蛇移动及加速功能设计 4.2 贪吃蛇吃食物加速及死亡判定功能的设计 4.3 贪吃蛇主动加速功能的设计 4.4 贪吃蛇奖励机制功能的设计 5.项目结构与项目实现 5.1 项目结构及类间关系 5.2 项目完整源码 1.开发环境及游戏展示 贪吃蛇大作战在设计与实验的过程中

  • IDEA SSM整合Redis项目实例 附源码

    IDEA SSM整合Redis项目实例 1.pom.xml 配置 <!-- https://mvnrepository.com/artifact/redis.clients/jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dep

  • Golang连接Redis数据库的方法

    Golang连接Redis数据库 golang连接数据库,这里博主推荐使用go-redis这个库,理由很简单(连接数据库的操作类似在数据库里面输入命令) go-redis的安装方式 go get -v https://github.com/go-redis/redis -v小v,是输出过程.一般情况下不带-v什么反馈都看不到. 连接redis的方式 package ... import ( "github.com/go-redis/redis" ) func main() { clie

  • springboot 如何使用jedis连接Redis数据库

    springboot 使用jedis连接Redis数据库 1. 在 pom.xml 配置文件中添加依赖 <!-- redis 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- jedis 依赖

  • Spring AOP实现Redis缓存数据库查询源码

    应用场景 我们希望能够将数据库查询结果缓存到Redis中,这样在第二次做同样的查询时便可以直接从redis取结果,从而减少数据库读写次数. 需要解决的问题 操作缓存的代码写在哪?必须要做到与业务逻辑代码完全分离. 如何避免脏读? 从缓存中读出的数据必须与数据库中的数据一致. 如何为一个数据库查询结果生成一个唯一的标识?即通过该标识(Redis中为Key),能唯一确定一个查询结果,同一个查询结果,一定能映射到同一个key.只有这样才能保证缓存内容的正确性 如何序列化查询结果?查询结果可能是单个实体

  • 关于Redis网络模型的源码详析

    前言 Redis的网络模型是基于I/O多路复用程序来实现的.源码中包含四种多路复用函数库epoll.select.evport.kqueue.在程序编译时会根据系统自动选择这四种库其中之一.下面以epoll为例,来分析Redis的I/O模块的源码. epoll系统调用方法 Redis网络事件处理模块的代码都是围绕epoll那三个系统方法来写的.先把这三个方法弄清楚,后面就不难了. epfd = epoll_create(1024); 创建epoll实例 参数:表示该 epoll 实例最多可监听的

  • 最优雅地整合 Spring & Spring MVC & MyBatis 搭建 Java 企业级应用(附源码)

    这里使用 Maven 项目管理工具构建项目 初始化项目 打开 Intellij IDEA,点击 Create New Project 选择 Maven 构建项目 选择 JDK 版本 选择 maven-archetype-webapp 模板(Java Web 项目) 填写项目在 Maven 仓库中的坐标(在 Maven 仓库中根据这个坐标才能找到该项目) 选择 Maven 路径 选择 Maven 配置文件路径 选择 Maven 本地仓库路径 填写项目名 选择工作目录 创建目录 在 src > ma

随机推荐