SpringBoot中的Cache缓存(二)

1.依赖包

		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>4.2.5.RELEASE</version>
		</dependency>

2.启动main方法添加缓存注解

@EnableCaching

3.实体类实现序列化接口

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User implements Serializable{
    private int id;
    private String name;

}

4.mapper

@Mapper
public interface UserMapper {

    //@Select("SELECT * FROM USER WHERE id = #{id}")
    User findByName(@Param("id") int id);

    @Insert("INSERT INTO USER(NAME) VALUES(#{name})")
    int insert(@Param("name") String name);

    @Update("update user set name =#{name} where id=#{id}")
    int update(@Param("id") int id,@Param("name") String name);

    @Delete("delete from user where id =#{id}")
    int delete(@Param("id") int id);

5.service:

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;


    //缓存key为id的数据到缓存boy中
    @Cacheable(value = "User",key = "#p0")
    public User findByName(int id) {
        User user=new User();
        user=userMapper.findByName(id);
        return user;
    }

    @CachePut(value = "User",key = "#p0.id")
    public User insert3(User user) {
        Integer count=userMapper.insert3(user);
        System.out.println(user.getId());
        return user;
    }
    //cacheput缓存新增的或者更新的数据到缓存,其中缓存名称为boy
    //数据的key是boy 的id
    @CachePut(value = "User",key = "#p0")
    public User update(int id, String name) {
        userMapper.update(id,name);
        User user=new User();
        user.setId(id);
        user.setName(name);
        return user;
    }
    @CacheEvict(value = "User",key = "#p0")
    public User delete(int id) {
        userMapper.delete(id);
        User user=new User();
        return user;
    }

6.controller:

	@RequestMapping("/select/{id}")
	@ResponseBody
	public void select(@PathVariable(value = "id") int id) {
		Object obj=userService.findByName(id);
		System.out.println(obj.toString());
	}

	@RequestMapping("/insert3")
	@ResponseBody
	public void insert3() {
		User user=new User();
		user.setName("555");
		userService.insert3(user);
		//System.out.println(userService.insert3(user));
	}

	@RequestMapping("/update/{id}/{name}")
	@ResponseBody
	public void update(@PathVariable(value = "id") int id,@PathVariable(value = "name") String name) {
		System.out.println(userService.update(id,name));
	}
	@RequestMapping("/delete/{id}")
	@ResponseBody
	public void delete(@PathVariable(value = "id") int id) {
		System.out.println(userService.delete(id));
	}

配置Configuration:

package com.sa.ch_5_2_3.common;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.annotation.EnableCaching;

import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import net.sf.ehcache.config.CacheConfiguration;

/**
 * Created by 123 on 2018-06-14
 */
@Configuration
@EnableCaching
public class CachingConfiguration implements CachingConfigurer {
    @Bean(destroyMethod="shutdown")
    public net.sf.ehcache.CacheManager ehCacheManager() {
        CacheConfiguration cacheConfiguration = new CacheConfiguration();
        //name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)。
        cacheConfiguration.setName("User");
        /**
         * 缓存的3 种清空策略 :
           1、FIFO ,first in first out (先进先出).
           2、LFU , Less Frequently Used (最少使用).意思是一直以来最少被使用的。
                缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存。
           3、LRU ,Least Recently Used(最近最少使用). (ehcache 默认值).
                缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,
                    那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
         */
        cacheConfiguration.setMemoryStoreEvictionPolicy("LRU");

        cacheConfiguration.setMaxEntriesLocalHeap(1000);
        //timeToIdleSeconds: 对象空闲时间,指对象在多长时间没有被访问就会失效。
        // 只对eternal为false的有效。默认值0,表示一直可以访问。
        cacheConfiguration.setTimeToIdleSeconds(1);
        //timeToLiveSeconds: 对象存活时间,指对象从创建到失效所需要的时间。
        // 只对eternal为false的有效。默认值0,表示一直可以访问。
        cacheConfiguration.setTimeToLiveSeconds(1);
        net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();
        config.addCache(cacheConfiguration);
        return net.sf.ehcache.CacheManager.newInstance(config);
    }

    @Bean
    @Override
    public CacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheManager());
    }

    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return new SimpleKeyGenerator();
    }

    @Override
    public CacheResolver cacheResolver() {

        return null;
    }

    @Override
    public CacheErrorHandler errorHandler() {
        return null;
    }

}

测试:

http://localhost:8082/insert3

插入成功后返回主键id.

查询:http://localhost:8082/select/33

报错,

{
    "msg": "Invalid bound statement (not found): com.sa.ch_5_2_3.mapper1.UserMapper.findByName",
    "code": 0,
    "obj": "http://localhost:8082/select/33"
}

因为设置的存活周期为一秒,而且sql的查询语句被注释掉了.

如果修改Configuration的配置时间,为600秒:

        //timeToIdleSeconds: 对象空闲时间,指对象在多长时间没有被访问就会失效。
        // 只对eternal为false的有效。默认值0,表示一直可以访问。
        cacheConfiguration.setTimeToIdleSeconds(600);
        //timeToLiveSeconds: 对象存活时间,指对象从创建到失效所需要的时间。
        // 只对eternal为false的有效。默认值0,表示一直可以访问。
        cacheConfiguration.setTimeToLiveSeconds(600);
则执行查询 http://localhost:8082/select/33,是可以在缓存中查询到内容。


猜你喜欢

转载自blog.csdn.net/qq_20867981/article/details/80695301
今日推荐