redis 基础认识
Redis是一个key-value存储系统。它是遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库。
Redis支持数据持久化可以吧内存中的数据存储到硬盘中,下次启动在加载使用,它可以支持简单的数据类型同样也支持 list、set、zset、hash 等数据存储,还支持数据备份 master-slave(主从模式)。
优势:丰富数据类型、丰富特性、 原子性(操作都是原子性的,意思是要么成功,要么失败)、性能高、
入/var/run/redis.pid,通过pidfile指定
默认监听端口 : 6379
String : set get (二进制安全)
Hash : hset hget (键值对集合,即编程语言中的Map类型)
List : lpush lrange (链表(双向链表))
Set : sadd smembers (哈希表实现,元素不重复)
Zset : zset zrangebyscore (将Set中的元素增加一个权重参数score,元素按score有序排列)
ping 测试redis是否启动
远程连接redis 数据库: -h 127.0.0.1 -p 6379 -a "mypass"
springboot redis MySQL
- 关于spring-redis
- 关于redis的key设计
- redis的基本数据结构
- 介绍redis与springboot的整合
- sringboot中的redistemplate的使用
- github 地址
1. 连接池自动管理,提供了一个高度封装的“RedisTemplate”类
2. 针对jedis客户端中大量api进行了归类封装,将同一类型操作封装为operation接口
ValueOperations:简单K-V操作
SetOperations:set类型数据操作
ZSetOperations:zset类型数据操作
HashOperations:针对map类型的数据操作
ListOperations:针对list类型的数据操作
springboot整合redis
啥也不说上代码通过maven 来管理jar
pom.xml文件
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.40</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- <exclusions>去掉springboot默认配置
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions> -->
</dependency>
<!-- <dependency> 引入log4j2依赖
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency> -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>1.1.3</version>
</dependency>
<!-- MyBatis 分页插件 PageHelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
boot 的配置文件 application.prooerties 配置文件
#\u7AEF\u53E3
server.port=9999
#JDBC
spring.datasource.url=jdbc:mysql://localhost:3306/tms?characterEncoding=utf8&useSSL=true&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#\u4E0B\u9762\u914D\u7F6E\u8BF4\u660E\u8BF7\u53C2\u8003Druid Github Wiki\uFF0C\u914D\u7F6E_StatViewServlet\u914D\u7F6E
#spring.datasource.druid.StatViewServlet.loginUsername=druid
#spring.datasource.druid.StatViewServlet.loginPassword=druid
#mybatis
mybatis.type-aliases-package=com.sk.entity
mybatis.mapper-locations=classpath:mapper/*.xml
#mappers \u591A\u4E2A\u63A5\u53E3\u65F6\u9017\u53F7\u9694\u5F00
#mapper.mappers=tk.mybatis.mapper.common.Mapper
mapper.mappers=com.sk.utils.MyMapper
mapper.not-empty=false
mapper.identity=MYSQL
mybatis.configuration.mapUnderscoreToCamelCase=true
#pagehelper
pagehelper.helperDialect=mysql
#pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
pagehelper.autoDialect=true
pagehelper.closeConn=false
pagehelper.reasonable=true
#audience.clientId=098f6bcd4621d373cade4e832627b4f6
#audience.base64Secret=MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=
#audience.name=restapiuser
#audience.expiresSecond=172800
## Redis \u914D\u7F6E
## Redis\u6570\u636E\u5E93\u7D22\u5F15\uFF08\u9ED8\u8BA4\u4E3A0\uFF09
spring.redis.database=0
## Redis\u670D\u52A1\u5668\u5730\u5740
spring.redis.host=127.0.0.1
## Redis\u670D\u52A1\u5668\u8FDE\u63A5\u7AEF\u53E3
spring.redis.port=6379
## Redis\u670D\u52A1\u5668\u8FDE\u63A5\u5BC6\u7801\uFF08\u9ED8\u8BA4\u4E3A\u7A7A\uFF09
spring.redis.password=123456
## \u8FDE\u63A5\u6C60\u6700\u5927\u8FDE\u63A5\u6570\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09
spring.redis.jedis.pool.max-active=8
## \u8FDE\u63A5\u6C60\u6700\u5927\u963B\u585E\u7B49\u5F85\u65F6\u95F4\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09
spring.redis.jedis.pool.max-wait=-1
## \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5927\u7A7A\u95F2\u8FDE\u63A5
spring.redis.jedis.pool.max-idle=8
## \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5
spring.redis.jedis.pool.min-idle=0
## \u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09
spring.redis.timeout=5000
上面都上常规的配置文件 下面就是代码实现啦啦啦
Controller层
public ResponseEntity<JsonResult> getUserById (@PathVariable(value = "id") Integer id) {
log.info("根据ID获取用户信息");
JsonResult r = null;
try {
User user = userService.getUserById(id);
r = new JsonResult(user, "ok");
} catch (Exception e) {
r = new JsonResult(e.getClass().getName() + ":" + e.getMessage());
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
UserService
User getUserById(Integer id);
UserServiceImpl
实现验证缓存中是否存在数据,如果存在直接返回,不存在去数据库中查询同时放入缓存中和返回前端;
package com.sk.service.impl;
import java.util.ArrayList;
import java.util.List;
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.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.sk.entity.User;
import com.sk.mapper.UserMapper;
import com.sk.service.UserService;
/**
* 2019年3月12日 上午11:18:07
* @HXing xu
* sk-redis
*
**/
@Service
public class UserServiceImpl implements UserService {
private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
@Autowired
private UserMapper userDao;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
public User getUserById(Integer id) {
// TODO Auto-generated method stub\
// 从缓存中获取用户信息
String key = "user_"+id;
ValueOperations<Object, Object> operations = redisTemplate.opsForValue();
// 缓存存在
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
User user = (User) operations.get(key);
log.info("UserServiceImpl.getUserById() : 从缓存中获取了用户 >> " + user.toString());
return user;
}else {
// 从 DB 中获取城市信息
User user = userDao.getUserById(id);;
// 插入缓存
operations.set(key, user , 30 , TimeUnit.MINUTES);
return user;
}
}
@Override
public List<User> listUser() {
String key = "list_user";
ListOperations<Object, Object> operations = redisTemplate.opsForList();
// 缓存存在
boolean hasKey = redisTemplate.hasKey(key);
if(hasKey) {
Long i = operations.size(key);
List<Object> list = operations.range(key, 0, operations.size(key));
log.info("UserServiceImpl.getUserById() : 从缓存中获取了用户 >> " + list.toString());
List<User> u_List = new ArrayList<>();
// 将object 转为 实体类
for(Object user : list) {
User us = new User();
us = (User) user;
u_List.add(us);
}
return u_List;
}else {
List<User> list = userDao.selectAll();
for(User user : list) {
operations.leftPush(key, user);
}
return list;
}
}
@Override
public User getUserByName(String name) {
// TODO Auto-generated method stub
return userDao.getUserByName(name);
}
@Override
public long delUserById(Integer id) {
Long l = userDao.delUserById(id);
//如果缓存存在,删除缓存
String key = "user_" +id;
boolean haskey = redisTemplate.hasKey(key);
if(haskey) {
redisTemplate.delete(key);
}
return 1;
}
}
现在基本上可以测试了
这是测试结果 第一次查询的数据库 ,第二次查询的缓存
数据现在已经放到缓存中,
最后所有的代码都被上传到我的github喜欢的话,给个start