SpringBoot进行Redis的安装与使用

linux下的就不用说了

主要是说一下Windows下的操作

先下载redis的数据库
github下载redis

在这里插入图片描述

再下载desktop的操作界面
Gitee下载Redis的操作界面
在这里插入图片描述

客户端界面
在这里插入图片描述
在这里插入图片描述

启动服务

在这里插入图片描述
下面就可以操作了

Redis主要是为了解决数据库与客户端频繁访问的问题

第一次访问先将数据从数据库拿出来,再放入Redis中,下次再拿同样的数据可以直接先在Redis中寻找

下面是进行的一些测试代码

1.数据库设计

在这里插入图片描述

1.实体Books

package com.xuda.model;

public class Books {
    private Integer bookid;

    private String bookname;

    private Integer bookcounts;

    private String detail;

    public Integer getBookid() {
        return bookid;
    }

    public void setBookid(Integer bookid) {
        this.bookid = bookid;
    }

    public String getBookname() {
        return bookname;
    }

    public void setBookname(String bookname) {
        this.bookname = bookname;
    }

    public Integer getBookcounts() {
        return bookcounts;
    }

    public void setBookcounts(Integer bookcounts) {
        this.bookcounts = bookcounts;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }
}

2.BookMapper.java写法,因为我用的是SpringBoot进行连接Redis与MySQL数据库与Mybatis进行的操作

package com.xuda.mapper;

import com.xuda.model.Books;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Mapper
@Repository
public interface BooksMapper {
    int insert(Books record);

    int insertSelective(Books record);
    int select();
}

3.BookMapper.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.xuda.mapper.BooksMapper">
  <resultMap id="BaseResultMap" type="com.xuda.model.Books">
    <result column="bookID" jdbcType="INTEGER" property="bookid" />
    <result column="bookName" jdbcType="VARCHAR" property="bookname" />
    <result column="bookCounts" jdbcType="INTEGER" property="bookcounts" />
    <result column="detail" jdbcType="VARCHAR" property="detail" />
  </resultMap>
  <insert id="insert" parameterType="com.xuda.model.Books">
    insert into books (bookID, bookName, bookCounts, 
      detail)
    values (#{bookid,jdbcType=INTEGER}, #{bookname,jdbcType=VARCHAR}, #{bookcounts,jdbcType=INTEGER}, 
      #{detail,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.xuda.model.Books">
    insert into books
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="bookid != null">
        bookID,
      </if>
      <if test="bookname != null">
        bookName,
      </if>
      <if test="bookcounts != null">
        bookCounts,
      </if>
      <if test="detail != null">
        detail,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="bookid != null">
        #{bookid,jdbcType=INTEGER},
      </if>
      <if test="bookname != null">
        #{bookname,jdbcType=VARCHAR},
      </if>
      <if test="bookcounts != null">
        #{bookcounts,jdbcType=INTEGER},
      </if>
      <if test="detail != null">
        #{detail,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <select id="select" resultType="java.lang.Integer">
        select count(*) from books
    </select>
</mapper>

4.service层设计

package com.xuda.Service;

import com.xuda.model.Books;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-03-19 15:39
 */
public interface BookService {
    int insert(Books record);

    int insertSelective(Books record);
    int select();
}

5.ServiceImpl层,这里面又主要的Redis与数据库交互的代码

package com.xuda.Service.impl.Impl;

import com.xuda.Service.BookService;
import com.xuda.mapper.BooksMapper;
import com.xuda.model.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-03-19 15:42
 */
@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BooksMapper booksMapper;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Override
    public int insert(Books books) {
        return booksMapper.insert(books);
    }

    @Override
    public int insertSelective(Books books) {
        return booksMapper.insertSelective(books);
    }
    //需要注入redis模板

    @Override
    public int select() {
        //更新redistemplate 对象中spring容器中key的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        //1. 先去redis缓存查看
        /*Integer allStudentCount = (Integer) redisTemplate.opsForValue().get("allStudentCount");

        //判断是否有值
        if (allStudentCount == null ) {
            //如果没有值就去数据库查询
            System.out.println("从数据库查询");
            allStudentCount = booksMapper.select();
            //将查询的结果放入redis缓存中
            //其中每隔十五秒清一次redis缓存
            redisTemplate.opsForValue().set("allStudentCount",allStudentCount,15, TimeUnit.SECONDS);

        } else {
            System.out.println("从redis里面取出");
        }*/
        //上面的代码中多线程和高并发情况下会出现一种现象:缓存穿透
        //需要通过双重检测+同步代码块来解决以上出现的问题

        //先判断redis缓存取学生人数
        Integer allStudentCount = (Integer) redisTemplate.opsForValue().get("allStudentCount");
        if (allStudentCount == null) {
            //设置同步代码快
            synchronized (this){
                //再次从redis中获取学生人数
                allStudentCount = (Integer) redisTemplate.opsForValue().get("allStudentCount");
                //再次判断是否为空
                if (allStudentCount == null) {
                    System.out.println("从数据库进行查询 进入到mysql");
                    //从数据库进行查询
                    allStudentCount = booksMapper.select();
                    //放到redis缓存中
                    //设置缓存15后清除
                    redisTemplate.opsForValue().set("allStudentCount",allStudentCount,15, TimeUnit.SECONDS);

                } else {
                    System.out.println("从redis中查询到数据没查到");
                }
            }
        } else {
            System.out.println("从redis查询");
        }
        //有就直接返回
        return allStudentCount;
    }
    }


6.接着为Controller层

package com.xuda.Controller;

import com.xuda.Service.BookService;
import com.xuda.model.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-03-19 15:49
 */
@Controller
@RequestMapping(value = "books")
public class ControllerBook {
    @Autowired
    private BookService bookService;
    @RequestMapping(value = "findbook")
    public @ResponseBody Object findbook(){
        LinkedList<Object> objects = new LinkedList<>();
        Books books = new Books();
        books.setBookname("徐大大");
        books.setBookcounts(200);
        books.setDetail("nihao");
        int i = bookService.insertSelective(books);
        return i;
    }

    @RequestMapping(value = "/index")
    public @ResponseBody Object index() {
        return "hello spring easy to use!";
    }


    @RequestMapping(value = "/count")
    public @ResponseBody Object studentCount(){
        //固定一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        for (int i = 0; i < 10; i++) {
            //开启一个线程
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    Integer allStuentCount =bookService.select();
                }
            });
        }
        executorService.shutdown();
        Integer allStudentCount = bookService.select();
        return "学生总人数为" + allStudentCount;
    }
}

7.sql连接

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=

#&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai

8.pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.xuda</groupId>
    <artifactId>003-springboot-mybatis</artifactId>
    <version>1.0.0</version>
    <name>003-springboot-mybatis</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>

    </properties>
    <dependencies>
        <!--jdbc驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </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>
            <!--mbatisspringboot启动依赖-->
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <!--资源扫描-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <!--mybatis自动生成插件-->

            <plugin>
               <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.6</version>
                <configuration>
                    <!--配置文件的位置-->
                    <configurationFile>GeneratorMapper.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>


            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

结果

在这里插入图片描述
在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小徐同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值