您的位置:首页 > 数据库 > Redis

[置顶] 【二】Springboot+Mybatis+Redis实现用户信息查询缓存

2017-12-05 20:01 846 查看
本文继上篇,在权限控制的基础之上,整合了Redis对用户信息进行缓存,减轻对后台数据库操作的压力。

上篇文章链接点这里

整合Redis之后会采用Redis对用户登录信息进行计数,从而在用户输入密码超过限制时将其锁定,防止密码暴力破解。

1. 同样,先展示下效果,之后上代码

继上篇,登陆之后获得权限,然后点击userinfo,来到用户信息查询界面,如下图



输入用户信息之后,就开始查询了,这里就做个简单的demo,展示用户账号密码,过程同样是ajax交互;

当查询的用户没有在redis缓存中,则创建key-value对,保存在缓存中,下次再次查询时,直接从缓存中读取数据,而不从数据库读取。类似的,也可以在添加用户,删除用户,更新用户时对缓存进行操作,这里就不举例了。

当我们第一次查询用户id为1的信息时:



后台打印log信息:



当我们再次查询用户id1时,后台打印log信息:



2. 代码实现部分

首先是pom.xml 加入redis依赖包

<!-- Spring Boot Redis 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>


配置application.properties

########################################################
###datasource
########################################################
spring.datasource.url = jdbc:mysql://localhost:3306/logindemo
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
server.port=8080

########################################################
### Redis+Session
########################################################
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=0


到这里,redis和springboot就算整合完成了,需要注意的是,所有的实体类都必须实现序列化,否则会报错

用户信息查询代码,首先是用户类实体

import java.io.Serializable;

public class userInfo implements Serializable{
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

private String username;
private String password;
}


Dao层代码,这里采用mabatis注解形式,加入代码

@Select("SELECT * FROM userInfo where id=#{id}")
userInfo finduserById(@Param("id") int id);


Service层这里省略,上ServiceImpl代码,在这里,实现了对redis的缓存

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.kfit.core.service.UserInfoService;
import com.kfit.dao.UserDao;
import com.kfit.entity.userInfo;

@Service

public class UserInfoServiceImpl implements UserInfoService {
@Autowired
private UserDao userDao;
@Autowired
private RedisTemplate redisTemplate;
private static final Logger LOGGER = LoggerFactory.getLogger(UserInfoServiceImpl.class);
public userInfo findByUsername(String username) {
// TODO Auto-generated method stub
return userDao.finduserByName(username);
}
@Override
public userInfo findById(int id) {
// 从缓存中获取信息
String key = "user-" + id;
ValueOperations<String, userInfo> operations = redisTemplate.opsForValue();

// 缓存存在
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
userInfo user = operations.get(key);

LOGGER.info("从缓存中获取了用户 >> " +"id: "+ user.getId()+", username: "+user.getUsername()+",password: "+user.getPassword());
return user;
}
userInfo user;
// 从 DB 中获取用户信息
user = userDao.finduserById(id);

// 插入缓存
if(user!=null){
operations.set(key, user, 30, TimeUnit.SECONDS);
LOGGER.info("用户插入缓存 >> " +"id: "+ user.getId()+", username: "+user.getUsername()+",password: "+user.getPassword());
}

return user;
}

}


Controller部分,插入以下代码

@RequestMapping(value = "/findUser", method = RequestMethod.POST)
@ResponseBody
public userInfo findUser(@RequestParam("id") int id) {
return userInfoService.findById(id);
}


然后就是html的交互部分了

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script>

function sendAjax()
{
var id = $("#cityid").val();
$.ajax(
{
url:"/userInfo/findUser",
data:{"id":id},
type:"post",
dataType:"json",
success:function(data)
{
$("#erro").html("账号:"+data.username);
$("#erro1").html("密码:"+data.password);
$("#erro1").show();

},
error: function() {
$("#erro").html("查询失败");
$("#erro1").hide();
}
});
}
</script>
</head>
<body>

<h3>用户查询界面</h3>
<input type="text" name="cityid" id="cityid"/>
<h3 id="erro"></h3>
<h3 id="erro1"></h3>
<p><input type="button" onclick="sendAjax()" value="查询" id="ajaxLogin"/></p>

</body>
</html>


ok,到这里代码部分就完成啦。

3. 总结

redis和mysql都可以作为持久层,对数据进行保存,区别是:

redis数据是key-value的数据结构,value可以是list,set,hash,sortedset和String,并且保存在内存中,速度非常快,提高性能的时候可以使用,但同时因为保存在内存,需要更多资源。目前redis主要是用在缓存,消息队列和session共享上。

mysql的数据是储存在磁盘上,虽然性能没有redis好,但是不需要更多的资金投入维护。

因此mysql适合作为主要的数据库,redis作为辅助数据库,帮助mysql储存缓存信息,减轻后台对于数据库频繁操作的压力。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: