java cache_Java中常用缓存Cache机制的实现

一、什么是缓存?

缓存,就是将程序或系统经常要调用的对象存在内存中,以便其使用时可以快速调用,不必再去创建新的重复的实例。这样做可以减少系统开销,提高系统效率。

二、缓存的实现方式:

实现方式1:

内存缓存,也就是实现一个类中静态Map,对这个Map进行常规的增删查.。

importorg.springframework.stereotype.Component;importwww.mxh.com.usercache.entity.UserInfo;importjava.util.Calendar;importjava.util.Date;importjava.util.HashMap;/*** 基于hashMap实现的缓存管理*/@Componentpublic classUserCacheManager {/*** 用户信息缓存*/

private static HashMap userList = new HashMap<>();/*** 保存时间*/

private static int liveTime = 60;/*** 添加用户信息缓存

*@paramsessionId

*@paramuserInfo

*@return

*/

public static booleanaddCache(String sessionId,UserInfo userInfo){

userList.put(sessionId,userInfo);return true;

}/*** 删除用户缓存信息

*@paramsessionId

*@return

*/

public static booleandelCache(String sessionId){

userList.remove(sessionId);return true;

}/*** 获取用户缓存信息

*@paramsessionId

*@return

*/

public staticUserInfo getCache(String sessionId){returnuserList.get(sessionId);

}/*** 清除过期的用户缓存信息*/

public static voidclearData(){

Calendar nowTime=Calendar.getInstance();

nowTime.add(Calendar.MINUTE,-liveTime);

Date time=nowTime.getTime();for(String key : userList.keySet()){

UserInfo userInfo=userList.get(key);if(userInfo.getLogin_time() == null ||time.after(userInfo.getLogin_time())){

userList.remove(key);

}

}

}

}

实现方式2(使用spring支持的cache):

实现步骤:

第一步: 导入spring-boot-starter-cache模块

org.springframework.boot

spring-boot-starter-cache

第二步: @EnableCaching开启缓存

@SpringBootApplication

@EnableCachingpublic classSpringboot07CacheApplication {public static voidmain(String[] args) {

SpringApplication.run(Springboot07CacheApplication.class, args);

}

}

第三步: 使用缓存注解

UserInfoCacheController

importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.cache.annotation.CacheEvict;importorg.springframework.cache.annotation.CachePut;importorg.springframework.context.annotation.Scope;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.ResponseBody;importwww.mxh.com.usercache.dao.LoginMapper;importwww.mxh.com.usercache.entity.UserInfo;importwww.mxh.com.usercache.service.Impl.LoginServiceImpl;

@Scope("prototype")

@Controllerpublic classUserInfoCacheController {

@Autowired(required= true)privateLoginMapper loginMapper;

@AutowiredprivateLoginServiceImpl loginService;

@ResponseBody

@RequestMapping(value= "/user/cache/login",method =RequestMethod.GET)public voiduserLoginByCache(String username,String password){

UserInfo userInfo=loginService.UserLoginByCache(username, password);

System.out.println(userInfo);

}/*** 通过username删除单个用户缓存信息

*@paramusername*/@CacheEvict(value="userInfo",key="#username")

@ResponseBody

@RequestMapping(value= "/user/cache/delete",method =RequestMethod.GET)public voiddeleteUserInfoCache(String username) {

System.out.println("清除用户信息缓存");

}/*@Cacheable(value="userInfo",key="#username")

@ResponseBody

@RequestMapping(value = "/user/cache/select",method = RequestMethod.GET)

public UserInfo selectUserInfoCache(String username) {

System.out.println("清除用户信息缓存");

}*/

/*** 通过username修改单个用户缓存信息

*@paramusername

*@parampassword

*@paramage

*@paramsex

*@paramuser_id

*@return

*/@CachePut(value="userInfo",key = "#username")

@ResponseBody

@RequestMapping(value= "/user/cache/update",method =RequestMethod.GET)public UserInfo updateUserInfoCache(@RequestParam(required = false) String username,

@RequestParam(required= false) String password,

@RequestParam(required= false) Integer age,

@RequestParam(required= false) String sex,

@RequestParam(required= false) Long user_id) {

UserInfo userInfo=loginMapper.updateUserInfoById(username, password, age, sex, user_id);

System.out.println("1.更新用户缓存信息: " +userInfo);if(null ==userInfo){

userInfo=loginMapper.selectUserByUsernameAndPassword(username,password);

}

System.out.println("2.更新用户缓存信息: " +userInfo);returnuserInfo;

}

}

LoginServiceImpl

importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.cache.annotation.CacheConfig;importorg.springframework.cache.annotation.Cacheable;importorg.springframework.stereotype.Service;importwww.mxh.com.usercache.dao.LoginMapper;importwww.mxh.com.usercache.entity.UserInfo;importwww.mxh.com.usercache.service.LoginService;importwww.mxh.com.usercache.util.UserCacheManager;

/*定义缓存名称*/

@CacheConfig(cacheNames= "userInfo")

@Servicepublic class LoginServiceImpl implementsLoginService {

@Autowired(required= true)privateLoginMapper loginMapper;

/*将查询到的数据放入缓存,下次调用该方法会先去缓存中查询数据*/

@Cacheable(value= "userInfo", key = "#username")

@OverridepublicUserInfo UserLoginByCache(String username, String password) {

UserInfo userInfo=loginMapper.selectUserByUsernameAndPasswordWithCache(username, password);

System.out.println("用户缓存信息: " +userInfo);returnuserInfo;

}

}

LoginMapper

importorg.apache.ibatis.annotations.Param;importorg.apache.ibatis.annotations.Select;importorg.springframework.stereotype.Repository;importwww.mxh.com.usercache.entity.UserInfo;/*** 登陆dao层操作接口*/@Repositorypublic interfaceLoginMapper{

@Select("select * from user_info where username=#{username} and password=#{password}")

UserInfo selectUserByUsernameAndPassword(@Param("username") String username,

@Param("password") String password);

@Select("select * from user_info where username=#{username} and password=#{password}")

UserInfo selectUserByUsernameAndPasswordWithCache(@Param("username") String username,

@Param("password") String password);

@Select("update user_info set username=#{username},password=#{password},age=#{age},sex=#{sex} where user_id=#{user_id}")

UserInfo updateUserInfoById(@Param("username") String username,

@Param("password") String password,

@Param("age") intage,

@Param("sex") String sex,

@Param("user_id") longuser_id);/*@Select("insert into user_info (username,password,age,sex,user_id) values(#{username},#{password},#{age},#{sex},#{user_id})")

UserInfo saveUserInfo(@Param("username") String username,

@Param("password") String password,

@Param("age") int age,

@Param("sex") String sex,

@Param("user_id") long user_id);*/}

UserInfo(实体类)

importjava.io.Serializable;importjava.util.Date;public class UserInfo implementsSerializable {private static final long serialVersionUID = 1L;privateLong user_id;privateString username;privateString password;privateString sex;privateInteger age;privateDate login_time;publicLong getUser_id() {returnuser_id;

}public voidsetUser_id(Long user_id) {this.user_id =user_id;

}publicString getUsername() {returnusername;

}public voidsetUsername(String username) {this.username =username;

}publicString getPassword() {returnpassword;

}public voidsetPassword(String password) {this.password =password;

}publicString getSex() {returnsex;

}public voidsetSex(String sex) {this.sex =sex;

}publicInteger getAge() {returnage;

}public voidsetAge(Integer age) {this.age =age;

}publicDate getLogin_time() {returnlogin_time;

}public voidsetLogin_time(Date login_time) {this.login_time =login_time;

}

@OverridepublicString toString() {return "UserInfo{" +

"user_id=" + user_id +

", username='" + username + '\'' +

", password='" + password + '\'' +

", sex='" + sex + '\'' +

", age=" + age +

", login_time=" + login_time +

'}';

}

}

application.properties

server.port=8009spring.datasource.url=jdbc:mysql://localhost:3306/bank?useUnicode=true&characterEncoding=utf8

spring.darasource.username=root

spring.datasource.password=root

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# 目标缓存管理器

#spring.cache.type=SIMPLE

spring.cache.type=ehcache

spring.cache.ehcache.config=classpath:ehcache.xml

# 打印sql语句

logging.level.www.mxh.com.usercache.dao=debug

ehcache.xml

具体代码详见博客文件中的user_cache例子

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值