SpringBoot 缓存之redis 篇

项目目录结构

依赖包引入  

 <?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=5000
     
    logging.level.com.cwh.springbootCache=DEBUG

注: spring.redis.timeout=5000不能设为0,不然在连接redis时会出现以下错误:

Caused by: io.lettuce.core.RedisCommandTimeoutException: Command timed out

具体代码

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语句日志,而第二次之后则没有打印,说明缓存开启成功;
源码下载:https://github.com/Menc0/springbootCache

猜你喜欢

转载自blog.csdn.net/fmwind/article/details/83030744
今日推荐