In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what is the use of Redis in the project?" in the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Redis related configuration in springboot
1. Introduce dependency into pom.xml
Redis.clients jedis 2.9.0
2. The habit of springboot is better than configuration. The application.yml file is also used in the project to configure the basic configuration items of mysql. The configuration item for redis is also configured in application.yml.
Spring: datasource: # driver configuration information url: jdbc:mysql://localhost:3306/spring_boot?useUnicode=true&characterEncoding=utf8 username: root password: root type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver # configuration information of connection pool filters: stat maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20 redis: host: 127.0.0.1 port: 6379 password: pass1234 pool: max-active: 100 max-idle: 10 max-wait: 100000 timeout: 0springboot
The project operates redis in the RedisTemplate way, and you can also fully use JedisPool and Jedis to manipulate redis. The content of integration is also collected and integrated from the Internet. There are many ways and methods of online integration, including the use of annotations, the use of Jackson2JsonRedisSerializer to serialize and deserialize key value values, and so on. What I use here is a way that I think is easy to understand and grasp, based on JedisPool configuration, using RedisTemplate to operate redis.
Redis is placed in a separate package redis, in which the RedisConfig.java file is created first.
RedisConfig.java
@ Configuration@EnableAutoConfigurationpublic class RedisConfig {@ Bean @ ConfigurationProperties (prefix = "spring.redis.pool") public JedisPoolConfig getRedisConfig () {JedisPoolConfig config = new JedisPoolConfig (); return config;} @ Bean @ ConfigurationProperties (prefix = "spring.redis") public JedisConnectionFactory getConnectionFactory () {JedisConnectionFactory factory = new JedisConnectionFactory (); factory.setUsePool (true); JedisPoolConfig config = getRedisConfig (); factory.setPoolConfig (config) Return factory;} @ Bean public RedisTemplate getRedisTemplate () {JedisConnectionFactory factory = getConnectionFactory (); RedisTemplate template = new StringRedisTemplate (factory); return template;}}
Create an implementation class RedisServiceImpl for the RedisService interface in the package, which implements all the methods of the interface.
RedisServiceImpl.java
@ Service ("redisService") public class RedisServiceImpl implements RedisService {@ Resource private RedisTemplate redisTemplate; @ Override public boolean set (final String key, final String value) {boolean result = redisTemplate.execute (new RedisCallback () {@ Override public Boolean doInRedis (RedisConnection connection) throws DataAccessException {RedisSerializer serializer = redisTemplate.getStringSerializer (); connection.set (serializer.serialize (key), serializer.serialize (value)) Return true;}}); return result;} @ Override public String get (final String key) {String result = redisTemplate.execute (new RedisCallback () {@ Override public String doInRedis (RedisConnection connection) throws DataAccessException {RedisSerializer serializer = redisTemplate.getStringSerializer (); byte [] value = connection.get (serializer.serialize (key) Return serializer.deserialize (value);}}); return result;} @ Override public boolean expire (final String key, long expire) {return redisTemplate.expire (key, expire, TimeUnit.SECONDS) } @ Override public boolean remove (final String key) {boolean result = redisTemplate.execute (new RedisCallback () {@ Override public Boolean doInRedis (RedisConnection connection) throws DataAccessException {RedisSerializer serializer = redisTemplate.getStringSerializer (); connection.del (key.getBytes ()); return true;}}); return result;}}
Here, the specific bottom layer of the execute () method is not studied, only that it can operate on redis data.
The data saved by redis is stored in memory and hard disk, so it needs to be serialized; the StringRedisSerializer is used for serialization, but the generics in this way specify String and can only be passed in String. So the json string is used to do the redis interaction in the project.
Now that the integration of redis in springboot is complete, let's test it and use it.
5. Use redis in springboot projects
Here, you will test directly using the unit test class SpringbootApplicationTests that comes with the springboot project.
@ RunWith (SpringRunner.class) @ SpringBootTestpublic class SpringbootApplicationTests {private JSONObject json = new JSONObject (); @ Autowired private RedisService redisService; @ Testpublic void contextLoads () throws Exception {} / * insert string * / @ Testpublic void setString () {redisService.set ("redis_string_test", "springboot redis test") } / * get the string * / @ Test public void getString () {String result = redisService.get ("redis_string_test"); System.out.println (result);} / * insert object * / @ Test public void setObject () {Person person = new Person ("person", "male") RedisService.set ("redis_obj_test", json.toJSONString (person));} / * * get object * / @ Test public void getObject () {String result = redisService.get ("redis_obj_test"); Person person = json.parseObject (result, Person.class); System.out.println (json.toJSONString (person)) } / * insert object List * / @ Test public void setList () {Person person1 = new Person ("person1", "male"); Person person2 = new Person ("person2", "female"); Person person3 = new Person ("person3", "male"); List list = new ArrayList (); list.add (person1); list.add (person2) List.add (person3); redisService.set ("redis_list_test", json.toJSONString (list));} / * * get list * / @ Test public void getList () {String result = redisService.get ("redis_list_test"); List list = json.parseArray (result, String.class); System.out.println (list) } @ Test public void remove () {redisService.remove ("redis_test");}} class Person {private String name; private String sex; public Person () {} public Person (String name, String sex) {this.name = name; this.sex = sex;} public String getName () {return name } public void setName (String name) {this.name = name;} public String getSex () {return sex;} public void setSex (String sex) {this.sex = sex;}}
Here, we first inject redisService with the @ Autowired annotation, and then introduce fastjson's JSONObject class because we are interacting with json strings. Then, for convenience, add a Person inner class directly to the test class.
A total of tests: for string type access, for object type access, for list type access, in fact, the essence is converted to a json string. There is also to perform remove operations according to key.
Get the string:
Get the object:
Get list:
Redis manages client data:
This is the end of the content of "how to use Redis in the project". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.