博客详情

spring cache的使用 (原创)

作者: 朝如青丝暮成雪
发布时间:2019-04-18 11:44:13  文章分类:java编程   阅读(913)  评论(0)


SpringCacheConfig 配置类


package com.tingcream.pagehelper.configuration;

import java.util.HashSet;
import java.util.Set;

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class SpringCacheConfig extends CachingConfigurerSupport {

	 
    @Bean
    @Override
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        ConcurrentMapCache cache1 =  new  ConcurrentMapCache("goods");//缓存对象1 商品
        ConcurrentMapCache cache2 =  new  ConcurrentMapCache("user");//缓存对象2 用户
        Set caches=new HashSet();
        caches.add(cache1);
        caches.add(cache2);
        cacheManager.setCaches(caches);
        return cacheManager;
    }

    /**
     * 自动生成redisKey规则
     */
	@Bean
	@Override
	public KeyGenerator keyGenerator() {
		return (target, method, params) -> {
			StringBuilder sb = new StringBuilder();
			sb.append(target.getClass().getName());
			sb.append(":");
			sb.append(method.getName());
			for (Object param : params) {
				sb.append(":" + param.toString());
			}
			String rediskey = sb.toString();
			System.out.println("自动生成redis key: "+rediskey);
			return rediskey;
		};
	}
	   
}



 测试代码 

UserController.java


package com.tingcream.pagehelper.controller;

import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.tingcream.pagehelper.common.RetMsg;
import com.tingcream.pagehelper.model.User;
import com.tingcream.pagehelper.service.UserService;

@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService ;
	@Autowired
	private CacheManager cacheManager ;
	 
	
	@RequestMapping("/add")
	public  RetMsg add(User user) {
		 User u = userService.addUser(user);
		return RetMsg.success(u);
	}
	@RequestMapping("/update")
	public RetMsg  update(User user) {
		 User u =userService.updateUser(user);
		return  RetMsg.success(u);
	 
	}
	@RequestMapping("/findById")
	public RetMsg findById(Integer id) {
		 User user = userService.findById(id);
		 return  RetMsg.success(user);
	}
	@RequestMapping("/deleteById")
	public RetMsg deleteById(Integer id) {
		int  count= userService.deleteById(id);
		if(count>0) {
			return  RetMsg.success();
		}else {
			return RetMsg.fail();
		}
	}
	@RequestMapping("/deleteAll")
	public RetMsg deleteAll() {
		userService.deleteAll();
		return RetMsg.success();
	}
	
	@RequestMapping("/findUsers")
	public RetMsg findUsers(String username,String addr) {
	   List list=	userService.findUsers(username, addr);
	   return RetMsg.success(list);
	}
	
	@RequestMapping("/getUserFromCache")
	public RetMsg getUserFromCache(Integer id) {
		Collection cacheNames= cacheManager.getCacheNames();
		System.out.println("cacheNames:"+cacheNames);
		Cache cache = cacheManager.getCache("user");
		System.out.println(cache);
		ValueWrapper w =   cacheManager.getCache("user").get(id);
		if(w!=null) {
			return RetMsg.success(w.get());
		}else {
			return RetMsg.fail();
		}
	}
	
}


UserService.java


package com.tingcream.pagehelper.service;

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

import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.stereotype.Service;

import com.tingcream.pagehelper.mapper.UserMapper;
import com.tingcream.pagehelper.model.User;

@Service
@CacheConfig(cacheNames="user")
public class UserService {
	 @Autowired
	 private UserMapper userMapper ;
	 
    /**
     * 新增  缓存key为用户id
     * @param user
     * @return
     */
    @CachePut(key="#result.userId")
	public User addUser(User user) {
		user.setCreateTime(new Date());
		userMapper.save(user);
		return user;
	}
    /**
     * 修改 缓存key为用户id
     * @param user
     * @return
     */
    @CachePut(key="#result.userId",condition="#user.userId!=null")
	public User updateUser(User user) {
    	  if(user.getUserId()==null) {
    		  throw new RuntimeException("修改用户,用户id不能为空");
    	  }
		  userMapper.update(user);
		  return userMapper.findById(user.getUserId());
	}
  
    /**
     * 根据id查询
     * @param id
     * @return
     */
	@Cacheable(key="#id")
	public User findById(Integer id) {
		System.out.println("findById方法调用");
		return userMapper.findById(id);
	}
   
	/**
	 * 根据id删除
	 * @param id
	 * @return
	 */
	@CacheEvict(key="#id")
	public int deleteById(Integer id) {
		return userMapper.deleteById(id);
	}
	
	/**
	 * 根据用户名、地址等条件模糊查询 用户列表
	 * @param username 用户名
	 * @param addr 地址
	 * @return
	 */
	@Cacheable(keyGenerator="keyGenerator")
	//注: 这个keyGenerator是在SpringCacheConfig配置类中配置了的bean(缺省使用),故这里也省略。否则需要我们配置自定义的key生成器bean以供使用。
	public List<User> findUsers(String username,String addr){
		System.out.println("findUsers方法执行");
		 Map<String,Object> map =new HashMap<String,Object>();
		 map.put("username", username);
		 map.put("addr", addr);
		 return  userMapper.findUsers(map);
	 
	}
	
	
	/**
	 * 清除所有
	 */
	@CacheEvict(allEntries=true)
	public void deleteAll() {
		System.out.println("清除所有");
		userMapper.deleteAll();
		 
	} 

}



UserMapper.java


package com.tingcream.pagehelper.mapper;

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

import com.tingcream.pagehelper.model.User;

public interface UserMapper {
	public List findAll();          
   	public int save(User user);      
   	public int update(User user);     
   	public int deleteById(int id); 
   	public User findById(int id);
	public void deleteAll();
	
	public List findUsers(Map map);       
}


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.tingcream.pagehelper.mapper.UserMapper" >
  
   <insert id="save" parameterType="User" keyProperty="userId" useGeneratedKeys="true">
       INSERT INTO t_user(`userId`,`username`,`password`,`phone`,`email`,`addr`,`createTime`)
       VALUES(#{userId},#{username},#{password},#{phone},#{email},#{addr},#{createTime})
   </insert>
   <select id="findAll" resultType="User">
        SELECT  * FROM t_user
   </select>
   <update id="update" parameterType="User">
       update  t_user t
      <set>
      <if test="username!=null and username!='' " >
        t.username=#{username},
      </if>
      <if test="password!=null and password!='' " >
        t.password=#{password},
      </if>
      <if test="phone!=null and phone!='' " >
        t.phone=#{phone},
      </if>
      <if test="email!=null and email!='' " >
        t.email=#{email},
      </if>
      <if test="addr!=null and addr!='' " >
        t.addr=#{addr},
      </if>
      <if test="createTime!=null and createTime!='' " >
        t.createTime=#{createTime},
      </if>
     </set>
     where t.userId=#{userId}
   </update>
   <select id="findById" parameterType="int" resultType="User">
      SELECT  * FROM `t_user` t WHERE t.`userId`=#{_parameter}
    </select>
   <delete id="deleteById" parameterType="int"> 
      DELETE  FROM  t_user    WHERE userId=#{_parameter}
   </delete>
   <delete id="deleteAll">
     TRUNCATE TABLE t_user
   </delete>
   <select id="findUsers" parameterType="map" resultType="User">
      SELECT  * FROM `t_user` t 
      <where>
          <if test="username!=null and username!=''">
                   and  t.username like  concat('%',#{username},'%')
           </if>
          <if test="addr!=null and addr!=''">
                   and  t.addr like  concat('%',#{addr},'%')
           </if>
      </where>
   </select>
    
   
</mapper>



参考spring官方文档: https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#cache


关键字:  spring  cache
评论信息
暂无评论
发表评论

亲,您还没有登陆,暂不能评论哦! 去 登陆 | 注册

博主信息
   
数据加载中,请稍候...
文章分类
   
数据加载中,请稍候...
阅读排行
 
数据加载中,请稍候...
评论排行
 
数据加载中,请稍候...

Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1

鄂公网安备 42011102000739号