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);
    }
}

存的时候缓存中是这样的:


基本上集成并且带持久化就是这样的,这仅是我个人的一点学习心得!
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
非常感谢您的提问。以下是对于Java Spring Boot,PostgreSQL和Redis技术框架的描述。 1. Java Spring Boot Java Spring Boot是一个基于Spring框架的开源Java应用程序开发框架。它旨在简化Spring应用程序的配置和部署。Spring Boot可以大大简化Spring应用程序的开发过程,因为它可以自动配置很多东西。Spring Boot提供了很多功能,比如可嵌入的Tomcat服务器,自动配置的数据访问库等等。使用Spring Boot可以快速构建生产就绪的Java应用程序。 2. PostgreSQL PostgreSQL是一个高性能,可扩展的开源关系型数据库管理系统。它支持SQL标准并提供了很多高级功能,比如事务,崩溃恢复等等,可以处理大量并发连接。除此之外,它还支持复杂数据类型,如JSON和XML。PostgreSQL非常灵活和可定制,可以集成到各种应用程序中,以提供持久化和数据存储。 3. Redis Redis是一个基于内存的键值对存储系统,可用于数据缓存,以提高应用程序的性能。Redis还提供了许多数据结构,如列表,集合,哈希表等等。Redis很容易扩展并具有高可用性,因为它支持主从复制和分片机制。Redis还支持事务和Lua脚本,可以用于复杂操作。 以上是对于Java Spring Boot,PostgreSQL和Redis技术框架的简要描述。希望能够帮助您更好地了解这些技术,并应用它们于实际项目中。如果您还有其他问题,请随时向我提问,我会尽力回答。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值