springboot整合redis

  springboot2.0整合reids,发现网上的一些整合,尤其是连接池,连接工厂那块,总是方法过时什么的,下面采用如下代码:

加入jar包

 1 <dependency>
 2             <groupId>org.springframework.boot</groupId>
 3             <artifactId>spring-boot-starter-data-redis</artifactId>
 4         <!--     <exclusion>
 5                 <groupId>io.lettuce</groupId>
 6                 <artifactId>lettuce-core</artifactId>
 7             </exclusion> -->
 8         </dependency>
 9         <dependency>
10             <groupId>redis.clients</groupId>
11             <artifactId>jedis</artifactId>
12         </dependency>

写propertie

 1 spring.rabbitmq.addresses=192.168.135.129:5672
 2 spring.rabbitmq.username=guest
 3 spring.rabbitmq.password=guest
 4 spring.rabbitmq.virtual-host=/
 5 
 6 spring.redis.host=192.168.135.129
 7 spring.redis.port=6379
 8 spring.redis.database=0
 9 spring.redis.jedis.pool.max-active=10
10 spring.redis.jedis.pool.max-idle=5
11 spring.redis.jedis.pool.max-wait=-1
12 spring.redis.jedis.pool.min-idle=3

config类

  1 package com.sharp.forward.redis;
  2 
  3 import java.time.Duration;
  4 
  5 import org.springframework.beans.factory.annotation.Autowired;
  6 import org.springframework.beans.factory.annotation.Value;
  7 import org.springframework.cache.CacheManager;
  8 import org.springframework.cache.annotation.CachingConfigurerSupport;
  9 import org.springframework.cache.annotation.EnableCaching;
 10 import org.springframework.cache.interceptor.KeyGenerator;
 11 import org.springframework.context.annotation.Bean;
 12 import org.springframework.context.annotation.ComponentScan;
 13 import org.springframework.context.annotation.Configuration;
 14 import org.springframework.context.annotation.PropertySource;
 15 import org.springframework.context.annotation.PropertySources;
 16 import org.springframework.data.redis.cache.RedisCacheManager;
 17 import org.springframework.data.redis.connection.RedisConnectionFactory;
 18 import org.springframework.data.redis.connection.RedisPassword;
 19 import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
 20 import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
 21 import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
 22 import org.springframework.data.redis.core.RedisTemplate;
 23 import org.springframework.data.redis.core.StringRedisTemplate;
 24 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
 25 import org.springframework.data.redis.serializer.RedisSerializer;
 26 import org.springframework.data.redis.serializer.StringRedisSerializer;
 27 import org.springframework.stereotype.Component;
 28 
 29 import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
 30 import com.fasterxml.jackson.annotation.PropertyAccessor;
 31 import com.fasterxml.jackson.databind.ObjectMapper;
 32 import com.fasterxml.jackson.databind.ser.std.StringSerializer;
 33 
 34 import redis.clients.jedis.JedisPool;
 35 import redis.clients.jedis.JedisPoolConfig;
 36 
 37 /**
 38  * 新建配置类继承CachingConfigurerSupport类
 39  *
 40  */
 41 @Configuration
 42 @EnableCaching
 43 public class RedisConfig extends CachingConfigurerSupport{
 44     @Value("${spring.redis.host}")
 45     private String host;
 46     @Value("${spring.redis.port}")
 47     private Integer port;
 48     @Value("${spring.redis.database}")
 49     private Integer database;
 50     @Value("${spring.redis.jedis.pool.max-active}")
 51     private Integer maxActive;
 52     @Value("${spring.redis.jedis.pool.max-idle}")
 53     private Integer maxIdle;
 54     @Value("${spring.redis.jedis.pool.max-wait}")
 55     private Integer maxWait;
 56     @Value("${spring.redis.jedis.pool.min-idle}")
 57     private Integer minIdle;
 58     @Bean
 59     JedisConnectionFactory jedisConnectionFactory() {
 60 //        spring2.0的配置可以采用redis 独立配置RedisStandaloneConfiguration或者集群配置org.springframework.data.redis.connection.RedisClusterConfiguration.class
 61         RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration ();
 62 //    方式一:直接写死的方式
 63 //        redisStandaloneConfiguration.setHostName("192.168.135.129");
 64 //        redisStandaloneConfiguration.setPort(6379);
 65 //        redisStandaloneConfiguration.setDatabase(0);
 66 //        redisStandaloneConfiguration.setPassword(RedisPassword.of("123456"));
 67 //    方式二:配置文件方式
 68         redisStandaloneConfiguration.setHostName(host);
 69         redisStandaloneConfiguration.setPort(port);
 70         redisStandaloneConfiguration.setDatabase(database);
 71 
 72         JedisClientConfiguration.JedisClientConfigurationBuilder jedisClientConfiguration = JedisClientConfiguration.builder();
 73         jedisClientConfiguration.connectTimeout(Duration.ofMillis(15000));//  connection timeout
 74         JedisConnectionFactory factory = new JedisConnectionFactory(redisStandaloneConfiguration,
 75                 jedisClientConfiguration.build());
 76         
 77         return factory;
 78     }
 79 //    编写redids  key默认生成器
 80     @Override
 81     public KeyGenerator keyGenerator() {
 82         // TODO Auto-generated method stub
 83         return super.keyGenerator();
 84     }
 85 //    配置缓存管理
 86     @Bean
 87     public CacheManager cacheManage() {
 88 //        两种写法都行
 89 //        RedisCacheManager cacheManager = RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(jedisConnectionFactory()).build();
 90         RedisCacheManager cacheManager = RedisCacheManager.create(jedisConnectionFactory());
 91         return cacheManager;
 92     }
 93     
 94     @Bean 
 95     public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory connectionFactory){
 96 //        设置序列化
 97 //        为给定目标类设置序列化
 98         Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
 99         ObjectMapper om = new ObjectMapper();
100 //        指定受影响的类型,属性描述符最小可见性
101         om.setVisibility(PropertyAccessor.ALL,Visibility.ANY);
102         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
103         jackson2JsonRedisSerializer.setObjectMapper(om);
104 //        配置redisTemplate
105         RedisTemplate<String,Object> redisTemplate = new RedisTemplate<String,Object>();
106         redisTemplate.setConnectionFactory(connectionFactory);
107         RedisSerializer stringSerializer = new StringRedisSerializer();
108         redisTemplate.setKeySerializer(stringSerializer);
109         redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
110         redisTemplate.setHashKeySerializer(stringSerializer);
111         redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
112         redisTemplate.afterPropertiesSet();
113         return redisTemplate;
114     }
115 
116 
117 }

实体

 1 package com.sharp.forward.redis;
 2 
 3 import java.io.Serializable;
 4 
 5 public class Order implements Serializable{
 6     private String id;
 7     private Integer number;
 8     private String name;
 9     public String getId() {
10         return id;
11     }
12     public void setId(String id) {
13         this.id = id;
14     }
15     public Integer getNumber() {
16         return number;
17     }
18     public void setNumber(Integer number) {
19         this.number = number;
20     }
21     public String getName() {
22         return name;
23     }
24     public void setName(String name) {
25         this.name = name;
26     }
27     
28 }

测试

 1 package com.sharp.forward;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 import org.junit.Test;
 7 import org.junit.runner.RunWith;
 8 import org.springframework.amqp.AmqpException;
 9 import org.springframework.amqp.core.Binding;
10 import org.springframework.amqp.core.Binding.DestinationType;
11 import org.springframework.amqp.core.DirectExchange;
12 import org.springframework.amqp.core.Message;
13 import org.springframework.amqp.core.MessageDeliveryMode;
14 import org.springframework.amqp.core.MessagePostProcessor;
15 import org.springframework.amqp.core.MessageProperties;
16 import org.springframework.amqp.core.Queue;
17 import org.springframework.amqp.rabbit.core.RabbitAdmin;
18 import org.springframework.amqp.rabbit.core.RabbitTemplate;
19 import org.springframework.beans.factory.annotation.Autowired;
20 import org.springframework.boot.test.context.SpringBootTest;
21 import org.springframework.data.redis.core.RedisTemplate;
22 import org.springframework.test.context.junit4.SpringRunner;
23 
24 import com.rabbitmq.client.AMQP;
25 import com.sharp.forward.redis.Order;
26 
27 @RunWith(SpringRunner.class)
28 @SpringBootTest
29 public class ForwardApplicationTests {
30     @Autowired
31     private RabbitAdmin rabbitAdmin;
32     @Test
33     public void contextLoads() {
34     }
35     
36     @Test
37     public void manager() {
38         rabbitAdmin.declareQueue(new Queue("admin_test", true, false,false));
39         rabbitAdmin.declareExchange(new DirectExchange("admin_exchange", true, false));
40         rabbitAdmin.declareBinding(new Binding("admin_test", DestinationType.QUEUE, "admin_exchange", "mq.direct", null));
41         rabbitAdmin.purgeQueue("queue_test", false);
42         rabbitAdmin.deleteQueue("admin_test");
43         rabbitAdmin.deleteExchange("admin_exchange");
44     }
45     @Autowired
46     private RabbitTemplate template;
47     @Test
48     public void sedMsg() {
49         String body = "hello.object rabbitmq!";
50         MessageProperties properties = new MessageProperties();
51         properties.setContentEncoding("utf-8");
52         properties.setContentType("text");
53         properties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
54         properties.setHeader("key1", "value");
55         Message msg = new Message(body.getBytes(), properties);
56         template.convertAndSend("ex001","mq.direct", msg, new MessagePostProcessor() {
57             
58             @Override
59             public Message postProcessMessage(Message message) throws AmqpException {
60                 message.getMessageProperties().getHeaders().put("key1", "new value");
61                 return message;
62             }
63         });
64     }
65     
66     @Autowired
67     private RedisTemplate redisTemplate;
68     @Test
69     public void redisWork() {
70         redisTemplate.opsForValue().set("test", "test002");
71     }
72     @Test
73     public void redisSave() {
74         Order order = new Order();
75         order.setId("001");
76         order.setName("订单001");
77         order.setNumber(20);
78         redisTemplate.opsForValue().set("order:", order);
79         Order order1=(Order) redisTemplate.opsForValue().get("order:");
80         System.out.println(order1.getName());
81         
82     }
83 }

测试OK!

原文地址:https://www.cnblogs.com/xiaoyao-001/p/9625781.html