Getting a Redis integration SpringBoot

0.Redis About
redis is an open source, advanced key-value store, it can be used to build high-performance storage solutions. redis a NoSql (Not Only Sql), i.e., non-relational databases, as well as commonly used NoSql MongoDB like. Redis can store the mapping between the key (key) and the value (value) five kinds of different data structures, the data structure of these five were String (String), List (list), the Set (set), the Hash (Powder column), and zSet (ordered set). Following table:

Profile data structure Redis
value data read and write data stored in the data type
String can be a string, integer, or float on the entire string part performs an operation; and a floating point execution target increment (INCREMENT) or decrement (Decrement)
List linked list, where each node contains a string pushed into or ejected from the both ends of the list elements; list of trimmed (tRIM) the offset; read a single or a plurality of elements; or shifted according to the value to look in addition to the elements
set collector comprising unordered string (unorderedcollection), and each string is contained in the different Add, Get, remove the individual elements; check whether there is an element in a set; calculating intersection, union, difference sets; obtaining random element from the collection
unordered hash containing a hash key for Add, Get, to remove a single key; get all of the keys
ZSet string member (member) and float ordered hash value between (score), elements are added the size of the order determined by the score, acquisition, removing single meta For; to obtain scores of elements according to the scope or members of
1.Redis dependency and configuration
we SpringBoot + MyBatis project-based, in which the integration of Redis. First, pom.xml introduced redis jar package:

<! - dependent incorporated redis ->

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Then, the resource profile application.yml (or properties) added redis configuration:

the Spring: 
Redis: 
#redis Address Database 
Host: localhost 
Port: 6379 
password: root 
timeout: 1000 
#redis database indexes, default 0 
Database: 1

spring.redis.database here is the index redis database, the default is 0. Since I redis local index database 0 items in use, so here is use an index database 1. It can be configured according to the actual situation.

Add operation 2.Redis of
developing a simple form page:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>userList</title>
<script src="../../js/jquery.min.js"></script>
<script src="../../js/layui/layui.js"></script>
<script src="../../js/vue.js"></script>
</head>
<body>
<div id="root">
添加用户:<br/>
姓名:<input type="text" v-model="userName"/><br/>
密码:<input type="text" v-model="password"/><br/>
电话:<input type="text" v-model="phone"/><br/>
<input type="button" @Click="addUser" value="提交"/>
    <input type="button" @Click="clearForm" value="提交"/>
</div>

<script>
new Vue({
el:"#root",
data:{
userName:"",
password:"",
phone:""
},
methods:{
addUser:function(){
var userDomain = {
userName: this.userName,
password:this.password,
phone:this.phone
};
$.ajax({
url:"/user/addUser",
type:"post",
contentType:"application/json",
data:JSON.stringify(userDomain),
success:function(data){
myVue.clearForm();
}
})
},
            clearForm:function(){
                this.userName = "";
                this.password = "";
                this.phone = "";
            }
}
})
</script>
</body>
</html>
 

  

Now, this page could not be simpler, it is to add a user form, and after receiving the ajax submit controller, and then to the service processing logic, let's look at the code level of service:

 

@Service(value="userService")
@Transactional
public class UserServiceImpl implements UserService{

@Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private UserMapper userMapper;
@Override
public int addUser(UserDomain user) {
int i = userMapper.insert(user);
if(i>0){
redisTemplate.opsForValue().set("user : "+user.getUserId(), JsonUtils.objectToJson(user));
}
return i;
}
}

  

Here we introduce StringRedisTemplate class, which is mainly used to integrate operations Redis class in Java. Used herein MyBatis first data to the database to add a user, if successfully added, opsForValue.set () method, Redis added to the database after the user data is formatted StringRedisTemplate Json is used in order to "user:" + the user's id attribute value as a key (MyBatis add operation has returned to the primary key). As follows:

Form action:

 

 

 

MySql:

 

 

 

Redis Desktop Manager:

 

 

 

We can see that we have successfully added the User object data, and MySql and Redis are already stored the data.

3.Redis query operation
Redis as NoSql technology flows among the most often used in the form of caching middleware, which mainly query operation, in many high concurrent access pressure, Redis made a lot of contribution. We all know that Mysql is persistent storage, stored on disk, will involve some IO, under high concurrency scenarios, this is a big bottleneck. Redis is running while residing in memory, which greatly improves access speed at high volume data. Combined with large amounts of data structures Redis provided (String, List, Set, ZSet, etc.), making it an alternative such as memcached, known as the most popular caching technology.

We first need a clear need such a thought, a query each time we need to go visit Redis, if to get the data directly back; if the data did not get the description of the record has not been cached or cache expiration, and then MySql need to get in, get after the data, copy it into a buffer.

Let's implement a simple hands Redis query results by userId input, query user object and returns to the front.

First of all, or write a simple form:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>userList</title>
<script src="../../js/jquery.min.js"></script>
<script src="../../js/layui/layui.js"></script>
<script src="../../js/vue.js"></script>
</head>
<body>
<div id="find">
输入需要查找的用户id:<br/>
id:<input type="text" v-model="userId"/><br/>
<input type="button" @Click="findUser" value="点我查找"/>
</div>
<script>
var findVue = new Vue({
el:"#find",
data:{
userId:""
},
methods:{
findUser:function(){
var id = this.userId;
if(/\D/.test(id)){
alert("只能输入数字");
this.userId = "";
return;
}
$.ajax({
url:"/user/findUser",
type:"get",
data:{userId:id},
contentType:"application/json",
success:function(data){
alert(data);
}
})
}
}
})

</script>
</body>
</html>

 

Controller层接收请求之后交给service层处理逻辑,来看一下service层的代码:

@Override
public UserDomain findUser(int userId){
UserDomain result = JsonUtils.jsonToPojo(redisTemplate.opsForValue().get("user : "+userId),UserDomain.class);
if(result == null){
result = userMapper.findUser(userId);
redisTemplate.opsForValue().set("user : "+result.getUserId(), JsonUtils.objectToJson(result));
}
return result;
}

逻辑非常简单,首先到Redis中查询,有数据直接返回;没有数据就去MySql中查询,将返回的结果复制到Redis中,以便下次查询时,不需要再访问Mysql。

这里并没有设置缓存时间等配置,我们到下一篇文章再来讲解这些。各位小伙伴可以自行测试一下。

 

Guess you like

Origin www.cnblogs.com/Koaler/p/11990314.html