Springboot启用ehcache缓存-创新互联

目录
  • 首先,添加依赖
  • 创建ehcache.xml配置文件
  • 修改springboot配置文件,引入ehcache.xml配置文件
  • 启用`@EnableCaching`注解
  • 实体类实现可序列化接口Serializable
  • 添加缓存注解`@Cacheable`、`@CacheEvict`
    • `@Cacheable`缓存数据
    • `@CacheEvict`清除缓存
  • 其它
    • 设置`java.io.tmpdir`子目录
  • 参考

创新互联建站专业为企业提供乐亭网站建设、乐亭做网站、乐亭网站设计、乐亭网站制作等企业网站建设、网页设计与制作、乐亭企业网站模板建站服务,十多年乐亭做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。首先,添加依赖
org.springframework.bootspring-boot-starter-cachenet.sf.ehcacheehcache
创建ehcache.xml配置文件
   
修改springboot配置文件,引入ehcache.xml配置文件
spring:
  cache:
    type: ehcache
    ehcache:
      config: classpath:ehcache/ehcache.xml
启用@EnableCaching注解
@SpringBootApplication
@EnableCaching
public class Application{public static void main(String[] args) {SpringApplication.run(Application.class, args);
    }
}
实体类实现可序列化接口Serializable

由于需要实体类支持缓存中的磁盘存储,所以需要实体类实现可序列化接口。

public class User implements Serializable{...
}
添加缓存注解@Cacheable@CacheEvict@Cacheable缓存数据
@Service
public class UserServiceImpl implements UserService {@Autowired
    private UserMapper userMapper;
    
    @Override
    @Cacheable(value="users")
    public User selectUserById(int id) {User user=this.userMapper.selectUserById(id);
        System.out.println("load data from db");
        return user;
    }
}
@CacheEvict清除缓存
@Service
public class UserServiceImpl implements UserService {@Autowired
    private UserMapper userMapper;
    
    @Override
    @Cacheable(value="users")
    public User selectUserById(int id) {User user=this.userMapper.selectUserById(id);
        System.out.println("load data from db");
        return user;
    }
    
	@CacheEvict(value="users", allEntries=true)
	public void saveUsers(Users users) {this.userMapper.save(users);
	}
	
	@CacheEvict(value="users", allEntries=true)
	public void deleteUserById(int id) {this.userMapper.deleteUserById(id);
	}
}
其它 设置java.io.tmpdir子目录
参考

https://www.cnblogs.com/xzmiyx/p/9897623.html
https://blog.csdn.net/qq_33285292/article/details/108152912

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


当前标题:Springboot启用ehcache缓存-创新互联
文章网址:http://pwwzsj.com/article/dedsej.html