Springboot整合redis及redis集群

  

1、maven依赖

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>


2、配置文件application.properties在添加配置:

  

#redis 集群

spring.redis.cluster.nodes=192.168.94.130:7000, 192.168.94.130:7001, 192.168.94.130:7002, 192.168.94.130:7003, 192.168.94.130:7004, 192.168.94.130:7005

  

  

#redis单个节点

#spring.redis.database=0

#spring.redis.host=192.168.94.130

#spring.redis.port=6379

#spring.redis.password=

#spring.redis.pool.max-idle=8

#spring.redis.pool.min-idle=0

#spring.redis.pool.max-active=8

#spring.redis.pool.max-wait=-1

#spring.redis.timeout=5000


3、redisTemplate测试:

@Autowired  

RedisTemplate redisTemplate;  

   

@Test  

public void redisTest() {  

    String key = "aaa";  

    String value = "bbb";  

       

    ValueOperations opsForValue = redisTemplate.opsForValue();  

       

    //数据插入

    opsForValue.set(key, value);  

    String valueFromRedis = opsForValue.get(key);  

    System.out.println(valueFromRedis)  

       

    //数据删除  

    redisTemplate.delete(key);  

    valueFromRedis = opsForValue.get(key);  

    System.out.println(valueFromRedis)   

}  

  

4.

Spring boot工程测试:

  

application.properties文件

server.port=8080

  

#mysql

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://192.168.94.130:3306/mytest

spring.datasource.username=xuhaixing

spring.datasource.password=xuhaixing

#spring.jpa.hibernate.naming-strategy=com.xhx.ms.entity.MySQLUpperCaseStrategy

  


#redis

#spring.redis.database=0

#spring.redis.host=192.168.94.130

#spring.redis.port=6379

#spring.redis.password=

#spring.redis.pool.max-idle=8

#spring.redis.pool.min-idle=0

#spring.redis.pool.max-active=8

#spring.redis.pool.max-wait=-1

#spring.redis.timeout=5000

  

  

#redis 集群

spring.redis.cluster.nodes=192.168.94.130:7000, 192.168.94.130:7001, 192.168.94.130:7002, 192.168.94.130:7003, 192.168.94.130:7004, 192.168.94.130:7005

#jpa

spring.jpa.database=mysql

spring.jpa.show-sql=true

spring.jpa.hibernate.ddl-auto=update

  

javaConfig

package com.xhx.ms.config;

  

import com.fasterxml.jackson.annotation.JsonAutoDetect;

import com.fasterxml.jackson.annotation.PropertyAccessor;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.sun.org.apache.xml.internal.utils.StringBufferPool;

import org.springframework.cache.CacheManager;

import org.springframework.cache.annotation.CachingConfigurerSupport;

import org.springframework.cache.annotation.EnableCaching;

import org.springframework.cache.interceptor.KeyGenerator;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.redis.cache.RedisCacheManager;

import org.springframework.data.redis.connection.RedisConnectionFactory;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import org.springframework.data.redis.serializer.StringRedisSerializer;

  

import java.lang.reflect.Method;

  

  

/**

* redis缓存配置

* Created by xuhaixing on 17-11-25.

*/

  

@Configuration

@EnableCaching//启用缓存

public class RedisCacheConfig extends CachingConfigurerSupport {

  

/**

* 自定义key,此方法会根据类名+方法名+所有参数的值生成一个

* 唯一的key,即@Cacheable中的key

*/

@Override

public KeyGenerator keyGenerator(){

return new KeyGenerator() {

@Override

public Object generate(Object o, Method method, Object... objects) {

StringBuilder sb = new StringBuilder();

sb.append(o.getClass().getName());

sb.append(method.getName());

for(Object obj:objects){

sb.append(obj.toString());

}

System.out.println(sb);

return sb.toString();

}

};

}

  

/**

* redisTemplate缓存操作类

* @param redisConnectionFactory

* @return

*/

@Bean

public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){

RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();

redisTemplate.setConnectionFactory(redisConnectionFactory);

// StringRedisSerializer redisSerializer = new StringRedisSerializer();

// redisTemplate.setKeySerializer(redisSerializer);

// redisTemplate.setHashKeySerializer(redisSerializer);

setSerializer(redisTemplate);

return redisTemplate;

}

private void setSerializer(RedisTemplate template) {

 Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(

Object.class);

ObjectMapper om = new ObjectMapper();

om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

jackson2JsonRedisSerializer.setObjectMapper(om);

template.setValueSerializer(jackson2JsonRedisSerializer);

template.setHashValueSerializer(jackson2JsonRedisSerializer);

}

  

/**

* 缓存管理器

*

*/

@Bean

public CacheManager cacheManager(RedisTemplate<?,?> redisTemplate){

RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);

redisCacheManager.setDefaultExpiration(3000);//s

return redisCacheManager;

}

  

}

  

  

  

Service注入缓存

 

package com.xhx.ms.service;

  

import com.xhx.ms.entity.Person;

import com.xhx.ms.repository.PersonRepository;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.CacheEvict;

import org.springframework.cache.annotation.Cacheable;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.core.ValueOperations;

import org.springframework.stereotype.Repository;

import org.springframework.stereotype.Service;

  

import javax.annotation.Resource;

  

/**

* Created by xuhaixing on 17-11-25.

*/

@Service

public class PersonService {

@Resource

private PersonRepository personRepository;

  

@Autowired

private RedisTemplate<String,Object> redisTemplate;

  

public void test(){

ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();

valueOperations.set("mykey1","random1="+Math.random());

System.out.println(valueOperations.get("mykey1"));

  

}

  

@Cacheable(value="person")

public Person findById(String id){

System.out.println("------findById-----id = "+id);

return personRepository.findOne(id);

}

  

// @CacheEvict(value="person",allEntries=true) //删除全部

@CacheEvict(value="person",key="'com.xhx.ms.service.PersonServicefindById'+#id") //删除指定

public void deleteFromCache(String id){

System.out.println("------deleteFromCache-----从缓存删除");

}

  

}

  

@Cacheable会记住请求参数和返回值,只有第一次请求时执行了方法,后面请求都没有执行方法,清楚缓存后又执行方法

  

  

主方法

package com.xhx.ms;

  

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

  

@SpringBootApplication

public class SpringbootRedisApplication {

  

public static void main(String[] args) {

SpringApplication.run(SpringbootRedisApplication.class, args);

}

}


  

  

  

满意请支持一下:


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的 SpringBoot 整合 Redis 集群的代码示例: 1. 添加 Redis 依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置 Redis 集群 在 application.properties 文件中添加以下配置: ```properties # 集群节点 spring.redis.cluster.nodes=redis://localhost:7001,redis://localhost:7002,redis://localhost:7003,redis://localhost:7004,redis://localhost:7005,redis://localhost:7006 # 连接超时时间 spring.redis.timeout=10000 # 最大重定向次数 spring.redis.cluster.max-redirects=3 ``` 3. 编写 RedisTemplate 配置类 ```java @Configuration public class RedisConfig { @Autowired private RedisConnectionFactory redisConnectionFactory; @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); // 设置序列化方式 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate; } } ``` 4. 使用 RedisTemplate 操作 Redis ```java @Service public class RedisService { @Autowired private RedisTemplate<String, Object> redisTemplate; public void set(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } } ``` 以上就是一个简单的 SpringBoot 整合 Redis 集群的代码示例。需要注意的是,Redis 集群配置方式可能因版本而异,请根据实际情况进行调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值