Spring+Redis集成+关系型数据库持久化
最近研究Spring-Redis集成的问题,在网上搜了很多,但是都是没有营养的资料,最后根据Spring和Redis官方文档加上不断实践,琢磨出的一点心得。 Redis是一个分布式的内存对象缓存系统,在我们的Web应用上集成中,有的用作持久化框架的二级缓存,有的用作一个单独的缓存系统,两者最终目的都是为了减小数据库服务器的压力,如果将Redis用作持久化框架的二级缓存,则显得有点大才小用,所以,我们将它独立出来,也方便以后的Redis集群。 在Spring-Redis集成中,在Spring的官方网站上有个Project是Spring-data-redis,其中就有我们需要的东西! 我们需要的jar包有两个:
1)spring-data-redis-1.1.1.RELEASE.jar
2)需要redis的java客户端,比较流行的java客服端有Jedis、JRedis,这里我们用最popular的Jedis客户端,jedis-2.1.0.jar
一、Spring的配置文件 官方的Jedis的Spring的配置文件如下: 如果采用模板的话,配置文件如下:
在这里我们需要进行修改,自定义自己的Spring配置文件,而且我们采用连接池的方式,从连接池中获取连接,Spring配置文件如下:
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig" > <!-- 最大活跃连接数 -->
<property name="maxActive" value="20" /> <!-- 最大闲置数量 -->
<property name="maxIdle" value="20" /> <!-- 最大等待时间 -->
<property name="maxWait" value="1000" /> <!-- 调用borrow 一个对象方法时,是否检查其有效性 -->
<property name="testOnBorrow" value="true"/> <!-- 调用return 一个对象方法时,是否检查其有效性 -->
<property name="testOnReturn" value="ture"/>
</bean>
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<!-- redis所在的ip -->
<property name="hostName" value="192.168.1.200"/>
<!-- redis的端口 -->
<property name="port" value="6379"/>
<!-- 是否启用连接池 -->
<property name="usePool" value="true"/>
<!-- 连接池的配置参考 -->
<property name="poolConfig" ref="jedisPoolConfig" />
</bean> 这样,在我们需要用到jedisConnectionFactory的类中,将jedisConnectionFactory注入进去,并从这个工厂获取JedisConnection对象。
二、测试
1)实体类:
public class Student implements Serializable { /** * */
private static final long serialVersionUID = 3951779424645593223L; private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() { return "Student [id=" + id + ", name=" + name + ", age=" + age + "]"; }
}
2)用Mybatis作为持久化框架,我们的Mapper是用注解形式写的:
public interface StudentMapper{
@Insert("insert into user(name,age) values(#{name},#{age})")
@Options(useGeneratedKeys=true,keyProperty="id")
int insert(Student student);
@Select("select * from user where id = #{id}")
Student queryById(@Param("id")int id);
}
3)service的实现类
public class StudentServiceImpl extends BaseService implements IStudentService{
private StudentMapper studentMapper;
private JedisConnectionFactory jedisConnectionFactory;
@Override
public void add(Student student){
studentMapper = writableSQLSession.getMapper(StudentMapper.class);
int id = studentMapper.insert(student);
System.out.println(id);
JedisConnection connection = jedisConnectionFactory.getConnection();
Map<byte[],byte[]> map = new HashMap<byte[],byte[]>();
map.put(SerializableUtil.serialize("name"), SerializableUtil.serialize(student.getName()));
map.put(SerializableUtil.serialize("age"), SerializableUtil.serialize(student.getAge()));
connection.hMSet(SerializableUtil.serialize(id), map);
}
@Override
public Student queryById(int id){
JedisConnection connection = jedisConnectionFactory.getConnection();
Map<byte[],byte[]> map = connection.hGetAll(SerializableUtil.serialize(id));
if(map.size() > 0){
System.out.println("----进缓存----");
byte[] byteName = map.get(SerializableUtil.serialize("name"));
byte[] byteAge = map.get(SerializableUtil.serialize("age"));
String name = SerializableUtil.unserialize(byteName).toString();
int age = Integer.valueOf(SerializableUtil.unserialize(byteAge).toString());
System.out.println(name);
System.out.println(age);
Student student = new Student();
student.setAge(age);
student.setName(name);
return student;
}else{
System.out.println("----进数据库----");
studentMapper = readonlySQLSession.getMapper(StudentMapper.class);
return studentMapper.queryById(id);
}
}
public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
this.jedisConnectionFactory = jedisConnectionFactory;
}
}
注意:
1)这里我用的数据库session是做了读写分离,并封装进BaseService中,在你做的时候,把它换成你自己的数据库Session就可以了!
2)存数据:
这里我用的向缓存中存对象的方法是用HashMap存的,这个和普通的键值对存放的方式有不同。
(1)普通键值对存放方式:
*************************************
* key * value *
* ***********************************
* key1 * value1 *
* key2 * value2 *
* key3 * value3 *
* ***********************************
(2)hashmap存放方式
例如我们存放Student对象,id:1,name:student1,age:18,其存放方式为:
***********************************************************
* key * value *
***********************************************************
* 1 * key * value * *
***************************************
* * name * student *
* * age * 18 *
***********************************************************
这样存的好处是键值对中的值也是采用键值对的方式进行存储,方便我们取值。
3)取数据:
我们首先根据序列化之后的id,去缓存中取,也是采用hashmap这种方式去取值,同时判断这个map的大小,如果有值,则取value中的值进行反序列化,然后返回对象,如果没有,则进数据库中去取值,然后在放入缓存中!
测试类:
public class TestRedis{
static IStudentService service;
@BeforeClass
public static void setUpBefor(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext/applicationContext.xml");
service = (IStudentService) context.getBean("studentService"); }
@Test
public void testAdd(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext/applicationContext.xml");
IStudentService service = (IStudentService) context.getBean("studentService");
Student student = new Student();
student.setName("student1");
student.setAge(29);
service.add(student);
}
@Test
public void testQuery(){
int id = 10;
Student student = service.queryById(id);
System.out.println(student);
}
}
存的时候缓存中是这样的: 基本上集成并且带持久化就是这样的,这仅是我个人的一点学习心得!
Spring+Redis集成+关系型数据库持久化的更多相关文章
- Redis非关系型数据库
1.简介 Redis是一个基于内存的Key-Value非关系型数据库,由C语言进行编写. Redis一般作为分布式缓存框架.分布式下的SESSION分离.分布式锁的实现等等. Redis速度快的原因: ...
- Redis 非关系型数据库 ( Nosql )
简介: Redis 是一个开源的,高性能的 key-value 系统,可以用来缓存或存储数据. Redis 数据可以持久化,并且支持多种数据类型:字符串(string),列表(list),哈希(has ...
- redis相对关系型数据库的优势
它是键值数据库(非关系),数据查询比关系型数据库快. ps:redis是树状结构,查询快 redis是基于内存的一个数据库,I/O的效率影响较小. ps: 备份数据同步是才进行I/O操作.这个数据同步 ...
- redis非关系型数据库的基本语法
导入并连接数据库: import redis # 导入redis模块,通过python操作redis 也可以直接在redis主机的服务端操作缓存数据库 import time # host是redis ...
- redis 非关系型数据库
redis 类型,数据存在磁盘里面,所以存储速度比较快,其他数据类型还是存储在数据库所以比较慢些 链接redis数据库: r=redis.Redis(host="%%%%%%%", ...
- Spring Boot集成H2数据库
需求 平时学习的时候,涉及到一些连接数据库相关的操作,经常需要初始化本地数据库,比如装个MySQL,初始化一些脚本,比较麻烦,H2是内存数据库,Spring Boot可以在应用启动的时候对H2数据库初 ...
- Redis (非关系型数据库) 数据类型 之 list列表类型
Redis列表是简单的字符串列表,按照插入顺序排序.你可以添加一个元素到列表的头部(左边)或者尾部(右边) list即可以作为“栈”也可以作为"队列". 操作: >lpush ...
- Redis (非关系型数据库) 数据类型 之 String类型
Redis 一个内存数据库,通过 Key-Value 键值对的的方式存储数据.由于 Redis 的数据都存储在内存中,所以访问速度非常快,因此 Redis 大量用于缓存系统,存储热点数据,可以极大的提 ...
- Spring单元测试集成H2数据库
项目源代码在:Spring-H2测试 H2简介 H2数据库是一种由Java编写的,极小,速度极快,可嵌入式的数据库.非常适合用在单元测试等数据不需要保存的场景下面. 以下时其官网的介绍: {% blo ...
随机推荐
- mysql中文查询问题
alter table t_foo change `str` `str` varchar(100) character set utf8 not null ;
- MongoDB设置连接池操作百万级以上数据
开发环境 spring 4.3.7 + springBoot 1.5.2 + dubbo 2.6.5 + mongoDB 4.0.0 连接池配置 mongo-pool.properties sprin ...
- SpringMVC避免IE执行AJAX,返回JSON出现下载文件
- dos命令 创建数据库,建表,两表联查,三表联查(mysql---第一篇)
首先打开mysql的控制台,输入密码进行登录 (ps:本文的mysql控制台,是运用的php的集成环境(phpstudy),点击运行,找到mysql命令行,直接打开就可以了) 登陆成功后,就可以进行 ...
- kubenetes安装记录和要点
https://blog.csdn.net/jinglexy/article/details/79813546 在官网web上进行kubenetes测试:kubectl run kubernetes- ...
- Xamarin.Android 报错问题
如果程序无法调试,输出中提示:(无法连接到logcat,GetProcessId 返回了:0) https://yq.aliyun.com/articles/618738
- Django ORM 常用字段和参数
Django ORM 常用字段和参数 一:常用字段 AutoField int自增列,必须填入参数 primary_key=True.当model中如果没有自增列,则自动会创建一个列名为id的列. I ...
- 201621123002《java程序设计》第九周学习总结
1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结集合与泛型相关内容. 1.2 选做:收集你认为有用的代码片段 //功能需求:将所有大于5的生成一个新的List对象 List lis ...
- MySQL 聚合函数 控制流程函数
常用的聚合函数 1. AVG() 求平均值 mysql> AVG([DISTINCT] expr) -- 返回 expr 的平均值 mysql> select AVG(age) from ...
- 腾讯开源的Paxos库PhxPaxos代码解读---Prepare阶段(一)
简单的画了一下PhxPaxos在Prepare阶段的逻辑,主要是正常的逻辑,异常逻辑和超时后面再写了; 熟悉PhxPaxos代码最好的方法是编译运行sample目录下的三个例子,编译方法在另一篇博客已 ...