文章目录
Redis缓存对象
修改原有查询逻辑
@RequestMapping(value = "/user/{userId}/evals/{commitId}", method = RequestMethod.GET)
//@ResponseBody
/**
* 查看
*/
public Map findCommitByCommitId(@PathVariable("userId") Integer userId, @PathVariable("commitId") Integer commitId) {
long startTime = System.currentTimeMillis();
Commit commit;
//1. 查询缓存
/*
Jedis jedis = new Jedis();
String key = "commit_" + commitId;
//从缓存获取对象序列化的结果
byte[] bytes = jedis.get(key.getBytes());
if (bytes == null) {
//2. 未找到数据
commit = dao.findCommitByCommitId(commitId);
System.out.println("从数据库取出信息");
//3. 放入缓存
bytes = SerializableUtil.serialize(commit);
jedis.set(key.getBytes(), bytes);
System.out.println("放入缓存完毕");
} else {
System.out.println("从Redis取出数据" + key + ":" + commitId);
//4. 取出信息并且反序列化
commit = (Commit) SerializableUtil.unserialize(bytes);
}
*/
//使用RedisTemplate
//1. 查询缓存
String key = "commit_" + commitId;
//2. 从缓存获取对象结果
commit = (Commit) redisTemplate.opsForValue().get(key);
if (commit == null) {
//3. 查询数据库
commit = dao.findCommitByCommitId(commitId);
System.out.println("从数据库取出" + key + "信息");
//4. 放入Redis
redisTemplate.opsForValue().set(key, commit);
System.out.println("放入Redis完成");
//清空列表缓存
String key1 = "user_commit_" + userId;
redisTemplate.delete(key1);
System.out.println("列表redis已清除:\t" + key1);
} else {
System.out.println("redis缓存已存在数据,本次查询读取redis");
}
//5. 响应输出
Map maps = new HashMap(3);
Integer status;
String msg;
if (commit != null) {
//新增成功
status = 200;
msg = "success";
} else {
//新增失败
status = 400;
msg = "failed";
}
maps.put("status", status);
maps.put("msg", msg);
maps.put("data", commit);
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间: " + (endTime - startTime) + "ms");
return maps;
}
注意
这样修改只是修改了查询逻辑,我们正常业务生产环境会涉及到增删改查等多方面应用,那么我们应该修改整个逻辑代码?并不需要,只要在控制器层修改好就行了
修改后的UserController
package mvc.controller;
import mvc.model.bean.Commit;
import mvc.model.dao.CommitDao;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Class Describe:
* 如果本控制器全都是@ResponseBody注解,那么可以直接添加@RestController
* <p>
* 查询密码为同一内容的所有用户
* GET http://localhost/user/xxx/users
* <p>
* 添加一个密码为xxx,账号名为xxx的用户
* POST http://localhost/user/xxx/users/xx
* <p>
* 查询密码为xxx的最新用户
* GET http://localhost/user/xxx/users/new
* <p>
* 删除密码为xxx的最老用户
* DELETE http://localhost/user/xxx/users/old
* <p>
* 更新密码为xxx的所有用户xx
* PUT http://localhost/user/xxx/users/xx
*
* @author biuaxia
* @date 2018/11/21
* @time 15:59
*/
//@Controller
@RestController
public class UserController {
@Resource
private CommitDao dao;
@Resource
private RedisTemplate redisTemplate;
/**
* 查询所有
*
* @return
*/
@RequestMapping(value = "/users")
public Map findAll() {
long startTime = System.currentTimeMillis();
//PageHelper.startPage(1, 3);
List<Commit> commits;
commits = dao.findAll();
Map maps = new HashMap(3);
if (commits.size() > 0) {
maps.put("status", 200);
maps.put("msg", "success");
} else {
maps.put("status", 400);
maps.put("msg", "failed");
}
maps.put("data", commits);
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间: " + (endTime - startTime) + "ms");
return maps;
}
@RequestMapping(value = "/user/{userId}/evals", method = RequestMethod.GET)
//@ResponseBody
/**
* 当前用户所有评价
*/
public Map findAllCommitByUserId(@PathVariable("userId") Integer userId) {
long startTime = System.currentTimeMillis();
List<Commit> commits;
String key = "user_commit_" + userId;
commits = (List<Commit>) redisTemplate.opsForValue().get(key);
if (commits == null) {
commits = dao.findAllByUserId(userId);
if (!commits.isEmpty()) {
//数据库中有数据才存入Redis
System.out.println("已压入Redis: " + key);
redisTemplate.opsForValue().set(key, commits);
}
}
Map maps = new HashMap(3);
Integer status;
String msg;
if (!commits.isEmpty()) {
//查询成功
status = 200;
msg = "success";
} else {
//查询失败
status = 400;
msg = "failed";
}
maps.put("status", status);
maps.put("msg", msg);
maps.put("data", commits);
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间: " + (endTime - startTime) + "ms");
return maps;
}
@RequestMapping(value = "/user/{userId}/evals", method = RequestMethod.POST)
//@ResponseBody
/**
* 添加
*/
public Map addNewCommitByUserIdAndContent(@PathVariable("userId") Integer userId, Commit commit) {
long startTime = System.currentTimeMillis();
Integer status = dao.addNewCommit(commit);
Map maps = new HashMap(3);
String msg;
if (status > 0) {
//新增成功
status = 200;
msg = "success";
System.out.println(commit.getCommit_Id());
String key = "commit_" + commit.getCommit_Id();
redisTemplate.opsForValue().set(key, commit);
System.out.println("新增数据成功,已存入redis缓存");
//清空列表缓存
String key1 = "user_commit_" + userId;
redisTemplate.delete(key1);
System.out.println("列表redis已清除:\t" + key1);
} else {
//新增失败
status = 400;
msg = "failed";
}
List<Commit> commits = dao.findAll();
maps.put("status", status);
maps.put("msg", msg);
maps.put("data", commits);
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间: " + (endTime - startTime) + "ms");
return maps;
}
@RequestMapping(value = "/user/{userId}/evals/{commitId}", method = RequestMethod.DELETE)
//@ResponseBody
/**
* 删除
*/
public Map delCommitByUserIdAndCommitId(@PathVariable("userId") Integer userId, @PathVariable("commitId") Integer commitId) {
long startTime = System.currentTimeMillis();
Integer status = dao.delCommit(commitId);
Map maps = new HashMap(3);
String msg;
if (status > 0) {
//删除成功
status = 200;
msg = "success";
//清空单个缓存
String key = "commit_" + commitId;
redisTemplate.delete(key);
System.out.println("单个redis已清除:\t" + key);
//清空列表缓存
String key1 = "user_commit_" + userId;
redisTemplate.delete(key1);
System.out.println("列表redis已清除:\t" + key1);
} else {
//删除失败
status = 400;
msg = "failed";
}
List<Commit> commits = dao.findAllByUserId(userId);
maps.put("status", status);
maps.put("msg", msg);
maps.put("data", commits);
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间: " + (endTime - startTime) + "ms");
return maps;
}
@RequestMapping(value = "/user/{userId}/evals/{commitId}", method = RequestMethod.GET)
//@ResponseBody
/**
* 查看
*/
public Map findCommitByCommitId(@PathVariable("userId") Integer userId, @PathVariable("commitId") Integer commitId) {
long startTime = System.currentTimeMillis();
Commit commit;
//1. 查询缓存
/*
Jedis jedis = new Jedis();
String key = "commit_" + commitId;
//从缓存获取对象序列化的结果
byte[] bytes = jedis.get(key.getBytes());
if (bytes == null) {
//2. 未找到数据
commit = dao.findCommitByCommitId(commitId);
System.out.println("从数据库取出信息");
//3. 放入缓存
bytes = SerializableUtil.serialize(commit);
jedis.set(key.getBytes(), bytes);
System.out.println("放入缓存完毕");
} else {
System.out.println("从Redis取出数据" + key + ":" + commitId);
//4. 取出信息并且反序列化
commit = (Commit) SerializableUtil.unserialize(bytes);
}
*/
//使用RedisTemplate
//1. 查询缓存
String key = "commit_" + commitId;
//2. 从缓存获取对象结果
commit = (Commit) redisTemplate.opsForValue().get(key);
if (commit == null) {
//3. 查询数据库
commit = dao.findCommitByCommitId(commitId);
System.out.println("从数据库取出" + key + "信息");
//4. 放入Redis
redisTemplate.opsForValue().set(key, commit);
System.out.println("放入Redis完成");
//清空列表缓存
String key1 = "user_commit_" + userId;
redisTemplate.delete(key1);
System.out.println("列表redis已清除:\t" + key1);
} else {
System.out.println("redis缓存已存在数据,本次查询读取redis");
}
//5. 响应输出
Map maps = new HashMap(3);
Integer status;
String msg;
if (commit != null) {
//新增成功
status = 200;
msg = "success";
} else {
//新增失败
status = 400;
msg = "failed";
}
maps.put("status", status);
maps.put("msg", msg);
maps.put("data", commit);
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间: " + (endTime - startTime) + "ms");
return maps;
}
@RequestMapping(value = "/user/{userId}/evals/{commitId}", method = RequestMethod.PUT)
/**
* 更新
*/
public Map editCommitByUserIdAndCommitIdAndContent(@PathVariable("userId") Integer userId, @PathVariable("commitId") Integer commitId, @RequestBody Commit commit) {
Map dbMap = new HashMap(2);
dbMap.put("commit", commit.getUser_Commit());
dbMap.put("commitId", commitId);
Integer status = dao.updateCommit(dbMap);
Map maps = new HashMap(3);
String msg;
if (status > 0) {
//更新成功
status = 200;
msg = "success";
} else {
//更新失败
status = 400;
msg = "failed";
}
/**
* 清空此时Redis的缓存
*/
String key = "commit_" + commitId;
//方法1,直接清空,简单
redisTemplate.delete(key);
//方法2,从数据库拿出来再塞回去
List<Commit> commits = dao.findAllByUserId(userId);
//清空列表缓存
String key1 = "user_commit_" + userId;
redisTemplate.delete(key1);
System.out.println("列表redis已清除:\t" + key1);
maps.put("status", status);
maps.put("msg", msg);
maps.put("data", commits);
return maps;
}
}
如何使用RedisTemplate
什么是RedisTemplate呢?
RedisTemplate对象是Spring-Data项目中提供的支持
什么是Spring-Data项目呢?
Spring Data 项目的目的是为了简化构建基于 Spring 框架应用的数据访问计数,包括非关系数据库、Map-Reduce 框架、云数据服务等等;另外也包含对关系数据库的访问支持。
Spring Data 包含多个子项目:
- Commons - 提供共享的基础框架,适合各个子项目使用,支持跨数据库持久化
- Hadoop - 基于 Spring 的 Hadoop 作业配置和一个 POJO 编程模型的 MapReduce 作业
- Key-Value - 集成了 Redis 和 Riak ,提供多个常用场景下的简单封装
- Document - 集成文档数据库:CouchDB 和 MongoDB 并提供基本的配置映射和资料库支持
- Graph - 集成 Neo4j 提供强大的基于 POJO 的编程模型
- Graph Roo AddOn - Roo support for Neo4j
- JDBC Extensions - 支持 Oracle RAD、高级队列和高级数据类型
- JPA - 简化创建 JPA 数据访问层和跨存储的持久层功能
- Mapping - 基于 Grails 的提供对象映射框架,支持不同的数据库
- Examples - 示例程序、文档和图数据库
- Guidance - 高级文档
如何使用RedisTemplate?
- 导入Spring-data-redis.jar和jedis.jar、commons-pool.jar包
- 创建连接池参数对象
JedisPoolConfig
- 创建连接池对象
JedisConnectionFactory
- 创建
RedisTemplate
- 给使用对象注入
RedisTemplate
示例代码
第一步:需要导入的包
第二步、第三步、第四步修改配置文件内容
SpringRedis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
<!--1. 配置连接bean-->
<bean id="config" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="1000"/>
<property name="minIdle" value="1"/>
</bean>
<!--2. 配置连接工厂|连接池对象-->
<bean id="redisFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="localhost"/>
<property name="port" value="6379"/>
<property name="poolConfig" ref="config"/>
</bean>
<!--3. 配置RedisTemplate-->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="redisFactory"/>
</bean>
</beans>
第五步:使用redisTemplate对象
RedisTemplateTest.java
package mvc.model.test;
import mvc.model.bean.Commit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.sql.Timestamp;
/**
* Class Describe:
*
* @author biuaxia
* @date 2018/11/27
* @time 18:11
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:SpringRedis.xml")
public class RedisTemplateTest {
@Resource
private RedisTemplate template;
@Test
public void test1() {
Commit commit = new Commit();
commit.setCommit_Id(3);
commit.setUser_Commit("大傻子");
commit.setUser_Commits_CreateTime(new Timestamp(System.currentTimeMillis()));
//存入
ValueOperations vo = template.opsForValue();
vo.set("commit_test", commit);
}
@Test
public void test2() {
//读取
ValueOperations vo = template.opsForValue();
Commit o = (Commit) vo.get("commit_test");
System.out.println(o.getUser_Commit());
}
}
MongoDB的安装与使用
说明
- 根据业界规则,偶数为“稳定版”(如:1.6.X,1.8.X),奇数为“开发版”(如:1.7.X,1.9.X),这两个版本的区别相信大家都知道吧。
- 32bit的mongodb最大只能存放2G的数据,64bit就没有限制。
安装流程
直接解压安装绿色版,目录不能包含中文
- 解压在非中文路径并记住路径名
- 在解压后的文件夹内新建log文件夹和data文件夹
- 在系统环境变量的
Path
中添加MongoDB的变量,路径为:解压路径/bin
- 解压文件夹
Shift+右键 -> 此处打开命令行窗口
执行命令解压路径>mongod --dbpath 解压路径/data
- 安装Windows服务就不用每次命令行启动,运行命令
解压路径>mongod --logpath 解压路径\logs\任意名称.log --logappend --dbpath 解压路径\data --serviceName (这里是服务名称,推荐括号外这个)MongoDB --install
安装完成后的一些启动参数和说明
数据文件目录:解压路径\data
, 并且参数--directoryperdb
说明每个DB都会新建一个目录;
Windows服务的名称:MongoDB
;
以上的三个参数都是可以根据自己的情况而定的,可以通过 mongod --help
查看更多的参数 。
最后是安装参数:--install
,与之相对的是--remove
- 启动MongoDB:
net start MongoDB
- 停止MongoDB:
net stop MongoDB
- 删除MongoDB:
sc delete MongoDB
启动MongoDB
上面的安装流程如果没有问题,输入启动命令后再直接Win+X
输入mongo
,出现如图界面即为成功
一些常见操作命令
在MongoDB的cmd窗口中,执行如下命令:
命令 | 说明 |
---|---|
show dbs | 查看当前有哪些数据库 |
use yourdb | 使用某个数据库 |
show collections | 查看本数据库中有哪些collection(表) |
db.yourCollection.find() | 查看yourCollection这张表存储的数据 |