1. 程式人生 > >19-SpringBoot之Redis(六)——Redis快取實現

19-SpringBoot之Redis(六)——Redis快取實現

SpringBoot之Redis(六)——Redis快取實現

1. 新增maven依賴

pom.xml檔案內容如下:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.springboot</groupId> <artifactId>cache</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging
>
<name>cache</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.0.RELEASE</version> <relativePath
/>
<!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</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>1.3.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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

2. 引數配置

application.yml檔案內容如下:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/redisCache?characterEncoding=UTF-8&serverTimezone=GMT
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    #預設隔離級別為讀寫提交
    tomcat:
      default-transaction-isolation: 2
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password:
    jedis:
      pool:
        max-active: 8
        max-wait: -1ms
        max-idle: 8
        min-idle: 0
    timeout: 2000ms
  #redis快取配置
  cache:
    type: redis
    cache-names: redisCache
    redis:
      #禁止字首
      use-key-prefix: false
      #自定義字首
      key-prefix:
      #允許儲存空值
      cache-null-values: true
      #定義超時時間,單位毫秒
      time-to-live: 600000
logging:
  config: classpath:logback-spring.xml
  path: D:/springbootLog/springboot

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.springboot.cache.model

3. 實體類

User.java


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * Created by HuangJun
 * 10:15 2018/11/26
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable{

    private static final long serialVersionUID = 7760614561073458247L ;

    private Integer id;
    private String username;
    private String birthday;
    private String sex;
    private String address;
}

4. Dao

UserDao.java

import com.springboot.cache.model.User;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by HuangJun
 * 10:22 2018/11/26
 */
@Repository
public interface UserDao {

    //獲取單個使用者
    User getUser(Integer id);

    //儲存使用者
    Integer insertUser(User user);

    //修改使用者
    Integer updateUser(User user);

    //查詢使用者,指定MyBatis 的引數名稱
    List<User> findUsers(User user);

    //刪除使用者
    int deleteUser(Integer id);
}

UserMapper.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.springboot.cache.dao.UserDao">

    <sql id="BASE_COLUMN">
      id,username,birthday,sex,address
    </sql>


    <select id="getUser" resultType="com.springboot.cache.model.User" >
        select
          <include refid="BASE_COLUMN"/>
        from user
        where id = #{id}
    </select>

    <insert id="insertUser" useGeneratedKeys="true" keyProperty="id"
            parameterType="com.springboot.cache.model.User">
        insert into user(username,birthday,sex,address)
        VALUES (#{username}, #{birthday}, #{sex}, #{address})
    </insert>

    <update id="updateUser">
        UPDATE USER
        <set>
            <if test="username!= null">
                 username = #{username},
            </if>
            <if test="birthday!= null">
                birthday = #{birthday},
            </if>
            <if test="sex!= null">
                sex = #{sex},
            </if>
            <if test="address!= null">
                address = #{address},
            </if>
        </set>

        WHERE  id = #{id}
    </update>


    <select id="findUsers" resultType="com.springboot.cache.model.User">
        <include refid="BASE_COLUMN"/>
        from user
        <where>
            <if test="username!= null">
                and username = #{username}
            </if>
            <if test="birthday!= null">
                and birthday = #{birthday}
            </if>
            <if test="sex!= null">
                and sex = #{sex}
            </if>
            <if test="address!= null">
                and address = #{address}
            </if>
        </where>
    </select>

    <delete id= "deleteUser">
      delete from user where id = #{id}
    </delete>


</mapper>

5. Service

UserService.java

import com.springboot.cache.model.User;

import java.util.List;

/**
 * Created by HuangJun
 * 10:46 2018/11/26
 */
public interface UserService {
    //獲取單個使用者
    User getUser(Integer id);

    //儲存使用者
    User insertUser(User user);

    //修改使用者
    User updateUser(User user);

    //查詢使用者,指定MyBatis 的引數名稱
    List<User> findUsers(User user);

    //刪除使用者
    int deleteUser(Integer id);
}

UserServiceImpl.java

import com.springboot.cache.dao.UserDao;
import com.springboot.cache.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
 * Created by HuangJun
 * 10:52 2018/11/26
 */
@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserDao userDao;

    @Override
    @Transactional
    @Cacheable(value = "redisCache", key = "'redis_user_' + #id")
    public User getUser(Integer id) {
        return userDao.getUser(id);
    }

    @Override
    @Transactional
    @CachePut(value = "redisCache", key = "'redis_user_' + #result.id")
    public User insertUser(User user) {
        userDao.insertUser(user);
        return user;
    }

    @Override
    @Transactional
    @CachePut(value = "redisCache",  key = "'redis_user_' + #result.id")
    public User updateUser(User user) {
        userDao.updateUser(user);
        return user;
    }

    @Override
    public List<User> findUsers(User user) {
        return userDao.findUsers(user);
    }

    @Override
    @Transactional
    @CacheEvict(value = "redisCache", key = "'redis_user_' + #id", beforeInvocation = false)
    public int deleteUser(Integer id) {
        return userDao.deleteUser(id);
    }
}

6. Controller

UserController.java

import com.springboot.cache.model.User;
import com.springboot.cache.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by HuangJun
 * 11:07 2018/11/26
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("createUser")
    public User createUser(User user){
        userService.insertUser(user);
        return user;
    }
    @PutMapping("updateUser")
    public User updateUser(User user){
        userService.updateUser(user);
        return user;
    }

    @GetMapping("findUsers")
    public List<User> findUsers(User user){
        return userService.findUsers(user);
    }

    @RequestMapping("getUser")
    public  Map<String,Object> getUser(Integer id){
        Map<String,Object> map = new HashMap<String,Object>();
        User user = userService.getUser(id);
        map.put("success",true);
        map.put("user",user);
        return map;
    }

    @RequestMapping("deleteUser")
    public Map<String,Object> deleteUser(Integer id){
        int ret = userService.deleteUser(id);
        Map<String,Object> map = new HashMap<String,Object>();
        if(ret==1){
            map.put("success",true);
            map.put("message","刪除成功");
        }else{
            map.put("success",false);
            map.put("message","刪除失敗");
        }
        return  map;
    }


}

7. 原始碼下載

原始碼下載地址:https://download.csdn.net/download/huangjun0210/10808220