Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the persistence of Relational Database with Spring+Redis Integration

2025-02-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "Spring+Redis integration how to achieve relational database persistence", the content of the article is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "Spring+Redis integration how to achieve relational database persistence" bar!

Redis is a distributed in-memory object caching system. In the integration of our Web application, some are used as the secondary cache of the persistence framework, and some are used as a separate cache system. The ultimate goal of both is to reduce the pressure on the database server. If Redis is used as the secondary cache of the persistence framework, it seems to be a bit too big and trivial, so we will separate it and facilitate the future Redis cluster. In Spring-Redis integration, there is a Project on the official website of Spring that is Spring-data-redis, and there is something we need! There are two jar packages we need:

1) spring-data-redis-1.1.1.RELEASE.jar

2) the java client of redis is required. The popular java customer service terminals are Jedis and JRedis. Here we use the most popular Jedis client, jedis-2.1.0.jar.

1. Spring configuration file the official Jedis Spring configuration file is as follows: if the template is used, the configuration file is as follows:

Here we need to make modifications to customize our own Spring configuration file, and we use connection pooling to obtain connections from connection pooling. The Spring configuration file is as follows:

So, in the class that we need to use jedisConnectionFactory, inject jedisConnectionFactory into it and get the JedisConnection object from the factory.

Second, testing

1) entity class:

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) using Mybatis as the persistence framework, our Mapper is written in the form of annotations:

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) the implementation class of 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 map = new HashMap ()

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 map = connection.hGetAll (SerializableUtil.serialize (id))

If (map.size () > 0) {

System.out.println ("- cached -")

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 ("- enter database -")

StudentMapper = readonlySQLSession.getMapper (StudentMapper.class)

Return studentMapper.queryById (id)

}

}

Public void setJedisConnectionFactory (JedisConnectionFactory jedisConnectionFactory) {

This.jedisConnectionFactory = jedisConnectionFactory

}

}

Note:

1) here I use the database session is to do read-write separation, and encapsulated in BaseService, when you do, change it to your own database Session on it!

2) Storage data:

The method I use here to store objects in the cache is stored in HashMap, which is different from ordinary key-value pairs.

(1) the storage mode of ordinary key-value pairs:

* *

* key * value *

* * *

* key1 * value1 *

* key2 * value2 *

* key3 * value3 *

* * *

(2) hashmap storage mode

For example, we store Student objects, id:1,name:student1,age:18, in the following ways:

* * *

* key * value *

* * *

* 1 * key * value * *

* *

* * name * student *

* * age * 18 *

* * *

The advantage of this kind of storage is that the value in the key-value pair is also stored in the way of key-value pair, which is convenient for us to take the value.

3) fetch data:

We first take the value from the cache according to the serialized id, and also use hashmap to get the value, and at the same time determine the size of the map. If there is a value, take the value in value for deserialization, and then return the object. If not, go to the database to fetch the value, and then put it in the cache!

Test class:

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)

}

}

Thank you for reading, the above is the content of "how to achieve relational database persistence in Spring+Redis integration". After the study of this article, I believe you have a deeper understanding of how to achieve relational database persistence in Spring+Redis integration, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report