SpringBoot 集成redis和redisTemplate

1、springboot配置文件application.yml

#端口
server:
  port: 8080

#模板页面
#注释的部分是Thymeleaf默认的配置,如有其它需求可以自行更改
spring.thymeleaf.cache: false
spring.thymeleaf.prefix: classpath:/templates/
spring.thymeleaf.suffix: .html
spring.thymeleaf.mode: LEGACYHTML5
spring.thymeleaf.encoding: UTF-8
spring.thymeleaf.content-type: text/html


#spring-boot整合单机版redis redis作为缓存
spring.redis.hostName: 192.168.1.103
spring.redis.port: 6379
spring.redis.password: xuan123456
spring.redis.database: 2 #默认使用db0
spring.redis.timeout: 0
spring.redis.pool.max-active: 8
spring.redis.pool.max-wait: -1
spring.redis.pool.max-idle: 8
spring.redis.pool.min-idle: 0




##数据源一
#spring:
#      datasource:
#          driverClass: com.mysql.jdbc.Driver
#          url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8
#          username: xuan
#          password: 123456
#数据源二
spring:
      datasource:
          url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8
          username: xuan
          password: 123456
          # 使用druid数据源
          type: com.alibaba.druid.pool.DruidDataSource
          driver-class-name: com.mysql.cj.jdbc.Driver
          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



#spring-boot整合mybatis
mybatis:
  #config-location: classpath:/mapper/config/mybatisConfig.xml #可以注射掉,没用到该配置文件
  mapper-locations: classpath:/mapper/*Mapper.xml
  #type-aliases-package: com.xuan.entity

2、maven配置文件加入依赖:



    4.0.0

    com.xuan
    myspringboot
    0.0.1-SNAPSHOT
    jar

    myspringboot
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.8.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8

        1.3.2
        6.0.6


        
        
        
        /Users/chenqixuan/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar
        ${basedir}/src/main/java
        ${basedir}/src/main/resources
        ${basedir}/src/main/java
        ${basedir}/src/main/resources/generator/generatorConfig.xml
        true
    

    

        
        
            
            
        

        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.1
        
        
        
            mysql
            mysql-connector-java
            ${mysql.connector.java.version}
        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
        
            com.alibaba
            druid
            1.0.11
        

        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            net.sourceforge.nekohtml
            nekohtml
            1.9.22
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                
                
                
                
                
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
            
                org.mybatis.generator
                mybatis-generator-maven-plugin
                ${mybatis.generator.version}
            
        
    

    
        
            spring-milestones
            Spring Milestones
            https://repo.spring.io/milestone
            
                false
            
        
    




3、springboot应用主入口开启缓存

package com.xuan;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@SpringBootApplication
@EnableCaching //开启缓存
@EnableTransactionManagement // 开启事务管理
@MapperScan("com.xuan.mapper") // 必须加这个,不加报错,如果不加,也可以在每个mapper上添加@Mapper注释,并且这里还要多填一个注释,那个我忘了,我一直用这个注解
public class MyspringbootApplication {

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

4、到这一步就可以使用redis缓存,要结合更高级的redisTemplate去使用redis还需要添加一些配置类

springboot主入口开启缓存后,可以使用redis 测试注解使用:

    @GetMapping(value="/one/{id}")
    @Cacheable(value = "getOneVideo")
    public Video getOneVideo(@PathVariable Integer id){
        System.out.println("没redis缓存");
        return videoMapper.selectByPrimaryKey(id);
    }

5、增加集成redistemplate配置(读取springboot配置文件的值的时候,名称注意一一对应,否则会读取不到)

package com.xuan.config;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by chenqixuan on 17/10/25.
 * 集成RedisTemplate
 */
@Configuration
@EnableAutoConfiguration
public class RedisConfig {

    private static Logger logger = Logger.getLogger(RedisConfig.class);

    //获取springboot配置文件的值 (get的时候获取)
    @Value("${spring.redis.hostName}")
    private String host;

    @Value("${spring.redis.password}")
    private String password;


    /**
     * @Bean 和 @ConfigurationProperties
     * 该功能在官方文档是没有提到的,我们可以把@ConfigurationProperties和@Bean和在一起使用。
     * 举个例子,我们需要用@Bean配置一个Config对象,Config对象有a,b,c成员变量需要配置,
     * 那么我们只要在yml或properties中定义了a=1,b=2,c=3,
     * 然后通过@ConfigurationProperties就能把值注入进Config对象中
     * @return
     */
    @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);
        logger.info("JedisConnectionFactory bean init success.");
        return factory;
    }


    @Bean
    public RedisTemplate getRedisTemplate() {
        JedisConnectionFactory factory = getConnectionFactory();
        logger.info(this.host+","+factory.getHostName()+","+factory.getDatabase());
        logger.info(this.password+","+factory.getPassword());
        logger.info(factory.getPoolConfig().getMaxIdle());
//        factory.setHostName(this.host);
//        factory.setPassword(this.password);
        RedisTemplate template = new StringRedisTemplate(getConnectionFactory());
        return template;
    }
}

6、基于redistemplate的工具类

package com.xuan.services.impl;

import com.xuan.services.RedisService;
import com.xuan.utils.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by chenqixuan on 17/10/25.
 *
 */
@Service
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 setList(String key, List list) {
        String value = JSONUtil.toJson(list);
        return set(key,value);
    }

    @Override
    public  List getList(String key, Class clz) {
        String json = get(key);
        if(json!=null){
            List list = JSONUtil.toList(json, clz);
            return list;
        }
        return null;
    }

    @Override
    public long lpush(final String key, Object obj) {
        final String value = JSONUtil.toJson(obj);
        long result = redisTemplate.execute(new RedisCallback() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer serializer = redisTemplate.getStringSerializer();
                long count = connection.lPush(serializer.serialize(key), serializer.serialize(value));
                return count;
            }
        });
        return result;
    }

    @Override
    public long rpush(final String key, Object obj) {
        final String value = JSONUtil.toJson(obj);
        long result = redisTemplate.execute(new RedisCallback() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer serializer = redisTemplate.getStringSerializer();
                long count = connection.rPush(serializer.serialize(key), serializer.serialize(value));
                return count;
            }
        });
        return result;
    }

    @Override
    public String lpop(final String key) {
        String result = redisTemplate.execute(new RedisCallback() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer serializer = redisTemplate.getStringSerializer();
                byte[] res =  connection.lPop(serializer.serialize(key));
                return serializer.deserialize(res);
            }
        });
        return result;
    }
}

7、Json工具类:利用了gson依赖

package com.xuan.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

/**
 * 
 * Created by chenqixuan on 17/10/25.
 * @desc json util 
 */
public class JSONUtil {
	
	private static Gson gson = null; 
	
	static{
		gson  = new Gson();//todo yyyy-MM-dd HH:mm:ss 
	}
	
	public static synchronized Gson newInstance(){
		if(gson == null){
			gson =  new Gson();
		}
		return gson;
	}
	
	public static String toJson(Object obj){
		return gson.toJson(obj);
	}
	
	public static  T toBean(String json,Class clz){
		
		return gson.fromJson(json, clz);
	}
	
	public static  Map toMap(String json,Class clz){
		 Map map = gson.fromJson(json, new TypeToken>(){}.getType());
		 Map result = new HashMap<>();
		 for(String key:map.keySet()){
			 result.put(key,gson.fromJson(map.get(key),clz) );
		 }
		 return result;
	}
	
	public static Map toMap(String json){
		 Map map = gson.fromJson(json, new TypeToken>(){}.getType());
		 return map;
	}
	
	public static  List toList(String json,Class clz){
		JsonArray array = new JsonParser().parse(json).getAsJsonArray();  
		List list  = new ArrayList<>();
		for(final JsonElement elem : array){  
	         list.add(gson.fromJson(elem, clz));
	    }
	    return list;
	}
	
	public static void main(String[] args) {
	}
	
}

8、使用:

package com.xuan.controller;

import com.xuan.config.RedisProperties;
import com.xuan.entity.Video;
import com.xuan.entity.VideoExample;
import com.xuan.mapper.VideoMapper;
import com.xuan.services.RedisService;
import com.xuan.services.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by chenqixuan on 17/10/25.
 */
@RestController
@RequestMapping("/video")
public class VideoController {

    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private VideoService videoService;

    @Autowired
    private RedisService redisService;


    @GetMapping(value="/redis/{id}")
    public List

效果图:

SpringBoot 集成redis和redisTemplate_第1张图片

图2:

SpringBoot 集成redis和redisTemplate_第2张图片

你可能感兴趣的:(Java,web,SpringBoot,Redis)