1. 程式人生 > >springboot系列 | 開啟快取(redis)

springboot系列 | 開啟快取(redis)

這篇基於redis在springboot中開啟快取處理

專案目錄結構


依賴包引入

<?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.cwh</groupId>
	<artifactId>springbootCache</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springbootCache</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.10.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-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.0</version>
		</dependency>
		
		<dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-data-redis</artifactId>  
        </dependency> 
		
		<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.29</version>
        </dependency>
	</dependencies>

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


</project>

配置檔案


spring.datasource.url=jdbc\:mysql\://127.0.0.1\:3306/springboots?useUnicode\=true&characterEncoding\=gbk&zeroDateTimeBehavior\=convertToNull
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# \u521D\u59CB\u5316\u5927\u5C0F\uFF0C\u6700\u5C0F\uFF0C\u6700\u5927  
spring.datasource.initialSize=5  
spring.datasource.minIdle=5  
spring.datasource.maxActive=20  
# \u914D\u7F6E\u83B7\u53D6\u8FDE\u63A5\u7B49\u5F85\u8D85\u65F6\u7684\u65F6\u95F4  
spring.datasource.maxWait=60000  
spring.datasource.show-sql=true 

mybatis.mapper-locations=classpath*:mapper/*Mapper.xml
mybatis.type-aliases-package=com.cwh.springbootMybatis.entity

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.database=1
spring.redis.pool.max-active=20
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=500
spring.redis.pool.min-idle=5
spring.redis.timeout=0

logging.level.com.cwh.springbootCache=DEBUG


具體程式碼

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.cwh.springbootCache.mapper.UserMapper">
 
  <select id="findUserInfo" resultType="com.cwh.springbootCache.entity.User" parameterType="java.lang.Integer">
    select id,name  from user where id=#{id}
  </select>
  <insert id="addUserInfo" parameterType="com.cwh.springbootCache.entity.User">
  	insert into user (id, name
      )
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}
      )
  </insert>
  <insert id="updateUserInfo" parameterType="com.cwh.springbootCache.entity.User">
  	update user set name=#{name} where id=#{id}
  </insert>
  <delete id="delUserInfo" parameterType="java.lang.Integer">
   delete from user where id = #{id,jdbcType=INTEGER}
  </delete>
 
</mapper>
UserMapper.java:
package com.cwh.springbootCache.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;

import com.cwh.springbootCache.entity.User;

@CacheConfig(cacheNames = "user")//快取名
@Mapper
public interface UserMapper {

	
	/**
	 * #p0代表第一個引數,也就是id,
	 * 先從redis的user快取物件裡去查詢key等於傳過來的id的值。如果沒有,就去查表
	 * @param id
	 * @return
	 */
	@Cacheable(key = "#p0")  
	public List<User> findUserInfo(int id);
	
	/**
	 * 代表往快取裡新增值,key為引數user的id屬性,
	 * 這樣當我們add一個User物件時,redis就會新增一個以id為key的User物件
	 * @param user
	 * @return
	 */
	@CachePut(key = "#p0.id")  
	public int addUserInfo(User user);
	
	/**
	 * 代表往快取裡修改值,key為引數user的id屬性,
	 * 這樣當我們update一個User物件時,redis就會修改一個以id為key的User物件,
	 * 如果id為key的User物件沒有,redis則新增一個以id為key的User物件
	 * @param user
	 * @return
	 */
	@CachePut(key = "#p0.id")  
	public int updateUserInfo(User user);
	
	/**
	 * 刪除快取
	 * @param id
	 * @return
	 */
	@CacheEvict(key = "#p0")  
	public int delUserInfo(int id);
}
說明:程式碼註釋裡以及寫明用法,這裡就不再贅述了


UserService.java:

package com.cwh.springbootCache.service;

import java.util.List;

import com.cwh.springbootCache.entity.User;

public interface UserService {
    public List<User> getUserInfo(int id);
    
    public void insert(User user);
    
    public void update(User user);
    
    public void delete(int id);
}
UserServiceImpl.java:
package com.cwh.springbootCache.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cwh.springbootCache.entity.User;
import com.cwh.springbootCache.mapper.UserMapper;
import com.cwh.springbootCache.service.UserService;

@Service
public class UserServiceImpl implements UserService{

	@Autowired
    private UserMapper userMapper;
	
	public void insert(User user) {
		userMapper.addUserInfo(user);
	}

	@Override
	public List<User> getUserInfo(int id) {
		return userMapper.findUserInfo(id);
	}

	@Override
	public void update(User user) {
		userMapper.updateUserInfo(user);
		
	}

	@Override
	public void delete(int id) {
		userMapper.delUserInfo(id);
	}
}
UserController.java:
package com.cwh.springbootCache.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cwh.springbootCache.entity.User;
import com.cwh.springbootCache.service.UserService;
  
@RestController  
@RequestMapping("/user")  
public class UserController {  
	@Autowired
	private UserService userService;
	
	@RequestMapping("/getUserInfo/{id}")
    public List<User> getUserInfo(@PathVariable("id")String id) {
		List<User> user = userService.getUserInfo(Integer.valueOf(id));
        System.out.println(user.toString());
        return user;
    }
	
	@RequestMapping("/addUserInfo")
    public String addUserInfo() {
		User user = new User();
		user.setId(4L);
		user.setName("cwh");
		userService.insert(user);
        return "success:"+user.toString();
    }
	
	@RequestMapping("/updateUserInfo")
	public String updateUserInfo() {
		User user = new User();
		user.setId(4L);
		user.setName("menco1");
		userService.update(user);
		return "success:"+user.toString();
	}
	
	@RequestMapping("/deleteUserInfo")
	public String deleteUserInfo() {
		userService.delete(4);
		return "success";
	}
	
	
}  

Application.java:

package com.cwh.springbootCache;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching  //開啟快取
public class Application{

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
	
}
注意:這裡需要用@EnableCaching開啟快取

執行測試

通過瀏覽器訪問,然後檢視控制檯列印日誌,可以發現第一次訪問日誌有列印相應的sql語句日誌,而第二次之後則沒有列印,說明快取開啟成功;