springBoot集成Redis

 今天需要完成一个新的功能,就是在查询接口查询到数据了,将查询 的数据缓存到redis,项目使用的框架为springBoot.

 因为很少用springboot框架,所以参考了网上springBoot集成redis的方法,最终将功能实现。

 现在讲集成redis的步骤记录一下:

      1、在配置文件配置redis的连接信息,在src/main/resources下面的配置文件application.properties文件里面配置


########################################################
###Redis (RedisConfiguration) create by kangjing 2018-04-25
########################################################
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=1
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.timeout=5000

      2、启动类添加@EnableCaching注解开启缓存

@SpringBootApplication
@EnableCaching
public class CallOutRecordApplication {

  public static void main(String[] args) {
		SpringApplication.run(CallOutRecordApplication.class, args);
	}
}

      3、添加RedisConfig配置文件

package com.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import com.callout.entity.RedisValue;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;


/**
 * Redis缓存配置类
 * @author kangjing 2018-04-25
 *
 */
@Configuration
@EnableCaching // 启用缓存特性
public class RedisConfig extends CachingConfigurerSupport {
	
	@Value("${spring.redis.host}")
	private String host;
	
	@Value("${spring.redis.port}")
	private String port;
	
	@Value("${spring.redis.password}")
	private String  password;
	
	@Value("${spring.redis.timeout}")
	private String timeout ;
	
	
	
	@Bean
    public RedisConnectionFactory redisCF(){
        //如果什么参数都不设置,默认连接本地6379端口
        JedisConnectionFactory factory = new JedisConnectionFactory();
        
        factory.setHostName(this.host);
        factory.setPassword(this.password);
        factory.setPort(Integer.valueOf(this.port));
        factory.setTimeout(Integer.valueOf(this.timeout));

        return factory;
    }

	
	/**
	 * 缓存管理器
	 * @param redisTemplate
	 * @return
	 */
	    @SuppressWarnings("rawtypes")
	    @Bean
	    public CacheManager cacheManager(RedisTemplate redisTemplate) {
	        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
	        //设置缓存默认的过期时间(秒)(全局的)
	        rcm.setDefaultExpiration(300);
	        return rcm;
	    }

	    @Bean
	    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
	        RedisTemplate<String , RedisValue> template = new RedisTemplate<String , RedisValue>();
	        template.setConnectionFactory(factory);
	        
	        ///设置序列化工具
	        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
	        ObjectMapper om = new ObjectMapper();
	        om.setVisibility(PropertyAccessor.ALL, com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY);
	        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
	        jackson2JsonRedisSerializer.setObjectMapper(om);
	        template.setValueSerializer(jackson2JsonRedisSerializer);
	       
	        template.afterPropertiesSet();
	        return template;
	    }
}

4、保存数据导redis

@Service
public class RecordService {
	@Autowired
	private RecordMapper recordMapper;
	
	
  @Autowired
  private RedisTemplate<String, RedisValue> template;//定义redis模板,这个模板的类型可以自己定义,但是需要和redisConfig里面定义的一样

	public RetRecord RecordCallOutQuery(Condition condition){
		
		//日表
		String tableName = getTableName(condition.getCallouttime());
		if("".equals(tableName)){
			return null;
		}
		//凭借被叫号码参数
		String telCalled = condition.getSyscode()+condition.getTelphone()+"%";
		//外呼开始时间减去30分钟
		String timeBefor = dealTate(condition.getCallouttime(),-30);
		//外呼开始时间加上30分钟
		String timeAfter = dealTate(condition.getCallouttime(),30);
		
		
		//录音记录查询
		List<RetList> retList = recordMapper.RecordCallOutQuery(tableName,telCalled,timeBefor,timeAfter);
	
		//将查询记录写入到redis  createby kangjing 2018-04-25
		saveRedis(retList);
}

/**
 * 将查询数据保存到redis  createby kangjing  2018-04-25
 * @param list
 */
public  void saveRedis(List<RetList> list){
	List<RedisValue>  redisList = new ArrayList<>();
	if(list != null && list.size() > 0){
		for(int i = 0; i < list.size() ;i++){
			RedisValue value = new RedisValue();
			value.setUuid(list.get(i).getUuid());
			value.setFtpIp(list.get(i).getFtpip());
			value.setFtpUserName(list.get(i).getFtpuser());
			value.setFtpPassWord(list.get(i).getFtppwd());
			value.setFilePath(list.get(i).getFilepath());
			template.opsForValue().set(value.getUuid(), value);//调用模板的方法保存数据导redis
		    }

	     }
	
     }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中集成Redis可以通过以下步骤实现: 1. 引入spring-boot-starter-data-redis依赖。在项目的pom.xml文件中,添加以下依赖项: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 这将自动引入与Redis集成所需的依赖项。 2. 在Spring Boot的核心配置文件application.properties中配置Redis连接信息。在该文件中添加以下配置项: ``` spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password=123456 ``` 根据你的实际情况,将host、port和password替换为相应的值。这些配置将用于建立与Redis服务器的连接。 通过以上步骤,你就成功地在Spring Boot应用程序中集成Redis。现在,你可以使用Spring Data Redis的API来访问和操作Redis数据库。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [SpringBoot集成redis](https://blog.csdn.net/qq_43512320/article/details/122684865)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [springboot集成Redis](https://blog.csdn.net/m0_54853420/article/details/126515971)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值