redis(10):spring+redis+mysql缓存实现

1 新建spring项目 

redis(10):spring+redis+mysql缓存实现_第1张图片

 

2 修改pom.xml



    4.0.0

    org.example
    spring-redis-mysql
    1.0-SNAPSHOT

    
        UTF-8
        1.7
        1.7
        3.5.2
        2.0.2
        4.3.24.RELEASE
        1.0.18
        8.0.17
        1.2.59
        
        1.2.17
        3.1.0
        1.18.10
    

    
        
        
            org.mybatis
            mybatis
            ${mybatis.version}
        
        
        
            org.mybatis
            mybatis-spring
            ${mybatis-spring.version}
        
        
        
            org.springframework
            spring-aspects
            ${spring.version}
        
        
            org.springframework
            spring-aop
            ${spring.version}
        
        
            org.springframework
            spring-context-support
            ${spring.version}
        
        
            org.springframework
            spring-context
            ${spring.version}
        
        
            org.springframework
            spring-core
            ${spring.version}
        
        
            org.springframework
            spring-jdbc
            ${spring.version}
        
        
        
            mysql
            mysql-connector-java
            ${mysql.version}
        
        
        
            com.alibaba
            fastjson
            ${fastjson.version}
        
        
        
            log4j
            log4j
            ${log4j.version}
        
        
            redis.clients
            jedis
            ${jedis.version}
        

        
        
            org.projectlombok
            lombok
            ${lombok.verison}
            provided
        


    

    
        
            
                
                
                    maven-clean-plugin
                    3.1.0
                
                
                
                    maven-resources-plugin
                    3.0.2
                
                
                    maven-compiler-plugin
                    3.8.0
                
                
                    maven-surefire-plugin
                    2.22.1
                
                
                    maven-jar-plugin
                    3.0.2
                
                
                    maven-install-plugin
                    2.5.2
                
                
                    maven-deploy-plugin
                    2.8.2
                
                
                
                    maven-site-plugin
                    3.7.1
                
                
                    maven-project-info-reports-plugin
                    3.0.0
                
            
        
    

3 新建User类

package com.example.demo.domain;

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

import java.io.Serializable;
import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    /**
     * 用户编号
     */
    private Integer id;

    /**
     * 用户姓名
     */
    private String name;

    /**
     * 用户地址
     */
    private String address;

    /**
     * 出生时间
     */
    private Date birth;

    /**
     * 是否删除1删除0未删除
     */
    private Integer flag;

    private static final long serialVersionUID = 1L;
}

4 新建UserMapper

package com.example.demo.mapper;

import com.example.demo.domain.User;

import java.util.List;

public interface UserMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);

    List queryAllUser();
}

5 生成UserMapper.xml




    
        
        
        
        
        
        
        
    
    
        
        id, `name`, address, birth, flag
    
    
    
        
        delete from sys_user
        where id = #{id,jdbcType=INTEGER}
    
    
        
        insert into sys_user (`name`, address, birth,
        flag)
        values (#{name,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR}, #{birth,jdbcType=TIMESTAMP},
        #{flag,jdbcType=INTEGER})
    
    
        
        insert into sys_user
        
            
                `name`,
            
            
                address,
            
            
                birth,
            
            
                flag,
            
        
        
            
                #{name,jdbcType=VARCHAR},
            
            
                #{address,jdbcType=VARCHAR},
            
            
                #{birth,jdbcType=TIMESTAMP},
            
            
                #{flag,jdbcType=INTEGER},
            
        
    
    
        
        update sys_user
        
            
                `name` = #{name,jdbcType=VARCHAR},
            
            
                address = #{address,jdbcType=VARCHAR},
            
            
                birth = #{birth,jdbcType=TIMESTAMP},
            
            
                flag = #{flag,jdbcType=INTEGER},
            
        
        where id = #{id,jdbcType=INTEGER}
    
    
        
        update sys_user
        set `name` = #{name,jdbcType=VARCHAR},
        address = #{address,jdbcType=VARCHAR},
        birth = #{birth,jdbcType=TIMESTAMP},
        flag = #{flag,jdbcType=INTEGER}
        where id = #{id,jdbcType=INTEGER}
    

    

6 生成UserService

package com.example.demo.service;

import com.example.demo.domain.User;

import java.util.List;

public interface UserService{

    int deleteByPrimaryKey(Integer id);

    User insert(User user);


    User selectByPrimaryKey(Integer id);


    User updateByPrimaryKey(User user);

    List queryAllUser();

}

7 生成UserServiceImpl

package com.example.demo.service.impl;


import com.example.demo.domain.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public int deleteByPrimaryKey(Integer id) {
        return this.userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public User insert(User user) {
        this.userMapper.insert(user);
        return user;
    }

    @Override
    public User selectByPrimaryKey(Integer id) {
        return this.userMapper.selectByPrimaryKey(id);
    }

    @Override
    public User updateByPrimaryKey(User user) {
        int index = this.userMapper.updateByPrimaryKey(user);
        return user;
    }

    @Override
    public List queryAllUser() {
        return this.userMapper.queryAllUser();
    }
}

8 创建application-redis.xml




    
    
        
        
        
        
        
    


    
    
        
        
        
        
        
        
    



9 创建application-dao.xml




    
    

    
    
        
        
        
        
        
    
    
    
        
        
        
        
            
                classpath:mapper/*Mapper.xml
            
        
    

    
    
        
        
            
                com.example.demo.mapper
            
        
        
        
    

10 创建application-service.xml




    

    
    
        
    
    
    
    
    
        
            
            
            
            
            
            
            
            
            
            
            
        
    
    
    
        
        
        
        
    

11 创建CacheUserAspect

package com.example.demo.cache;

import com.alibaba.fastjson.JSON;
import com.example.demo.domain.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.Serializable;

@Component
@Aspect
@EnableAspectJAutoProxy
public class CacheUserAspect {


    private Log log= LogFactory.getLog(CacheUserAspect.class);

    public static final String POINTCUT_ADD="execution(* com.example.demo.service.impl.UserServiceImpl.insert(..))";
    public static final String POINTCUT_UPDATE="execution(* com.example.demo.service.impl.UserServiceImpl.updateByPrimaryKey(..))";
    public static final String POINTCUT_DELETE="execution(* com.example.demo.service.impl.UserServiceImpl.deleteByPrimaryKey(..))";
    public static final String POINTCUT_GETONE="execution(* com.example.demo.service.impl.UserServiceImpl.selectByPrimaryKey(..))";

    //redis里面的前缀
    public static final String PROFIX="user:";

    //注入JedisPool
    @Autowired
    private JedisPool jedisPool;



    @Around(value = CacheUserAspect.POINTCUT_ADD)
    public Object cacheAddUser(ProceedingJoinPoint pjp) throws Throwable {
        //插入数据库
        User user = (User) pjp.proceed();
        Jedis jedis = jedisPool.getResource();

        //把user转成json串
        String json= JSON.toJSONString(user);
        jedis.set(PROFIX+user.getId(),json);
        log.info(PROFIX+user.getId()+"数据已存入到Redis");
        jedis.close();
        return user;
    }

    @Around(value = CacheUserAspect.POINTCUT_UPDATE)
    public Object cacheUpdateUser(ProceedingJoinPoint pjp) throws Throwable {
        //修改数据库
        User user = (User) pjp.proceed();
        Jedis jedis = jedisPool.getResource();
        //把user转成json串
        String json= JSON.toJSONString(user);
        jedis.set(PROFIX+user.getId(),json);
        log.info(PROFIX+user.getId()+"数据已更新到Redis");
        jedis.close();
        return user;
    }

    @Around(value = CacheUserAspect.POINTCUT_DELETE)
    public Object cacheDeleteUser(ProceedingJoinPoint pjp) throws Throwable {
        //删除数据库
        Serializable id = (Serializable) pjp.getArgs()[0];
        log.info(PROFIX+id+"数据库数据已删除");
        Jedis jedis = jedisPool.getResource();
        if(jedis.exists(PROFIX+id)){
            jedis.del(PROFIX+id);
            log.info(PROFIX+id+"数据已从Redis删除");
        }
        jedis.close();
        return id;
    }

    @Around(value = CacheUserAspect.POINTCUT_GETONE)
    public Object cacheGetOneUser(ProceedingJoinPoint pjp) throws Throwable {
        Serializable id = (Serializable) pjp.getArgs()[0];
        if(null==id){
            return null;
        }
        Jedis jedis = jedisPool.getResource();
        String json = jedis.get(PROFIX + id);
        if(null!=json){
            User user=JSON.parseObject(json,User.class);
            log.info(PROFIX+id+"已从redis里机查询到数据");
            jedis.close();
            return user;
        }else{
            log.info(PROFIX+id+"缓存里面没有数据,要从数据库里面查询");
            User user= (User) pjp.proceed();
            if(null!=user){
                jedis.set(PROFIX+user.getId(),JSON.toJSONString(user));
                log.info(PROFIX+id+"数据已存入redis");
            }
            jedis.close();
            return  user;
        }
    }



}

12 创建application-cache.xml




    

13 创建applicationContext.xml





    
    
    
    


14 TestApp测试类

package com.example.demo.test;

import com.example.demo.domain.User;
import com.example.demo.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Date;
import java.util.List;

public class TestApp {
    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

        UserService userService = context.getBean(UserService.class);


        List users = userService.queryAllUser();
        for (User user : users) {
            System.out.println(user);
        }
        User user=new User();
        user.setName("xiaoqiang");
        user.setAddress("bj");
        user.setBirth(new Date());
        user.setFlag(0);
        userService.insert(user);

//        User user = userService.selectByPrimaryKey(113);
//        System.out.println(user);
//        user.setName("xiaoming");
//        user.setAddress("wh");
//        userService.updateByPrimaryKey(user);

        
//        userService.deleteByPrimaryKey(112);

        System.out.println("操作成功");

    }
}

你可能感兴趣的:(Redis,缓存,redis,spring)