springboot整合redis

springboot-整合redis

springboot学习笔记-4 整合Druid数据源和使用@Cache简化redis配置

一.整合Druid数据源

  Druid是一个关系型数据库连接池,是阿里巴巴的一个开源项目,Druid在监控,可扩展性,稳定性和性能方面具有比较明显的优势.通过Druid提供的监控功能,可以实时观察数据库连接池和SQL查询的工作情况.使用Druid在一定程度上可以提高数据库的访问技能.

  1.1 在pom.xml中添加依赖

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.18</version>
</dependency>

  1.2 Druid数据源配置

  在application.properties中,去书写Druid数据源的配置信息.

##Druid##
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
spring.datasource.useGlobalDataSourceStat=true

  1.3 建立DruidConfiguration配置类,配置过滤信息

@Configuration
public class DruidConfiguration {
    @Bean
    public ServletRegistrationBean statViewServle(){
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
        //白名单:
        servletRegistrationBean.addInitParameter("allow","192.168.1.218,127.0.0.1");
        //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的即提示:Sorry, you are not permitted to view this page.
        servletRegistrationBean.addInitParameter("deny","192.168.1.100");
        //登录查看信息的账号密码.
        servletRegistrationBean.addInitParameter("loginUsername","druid");
        servletRegistrationBean.addInitParameter("loginPassword","12345678");
        //是否能够重置数据.
        servletRegistrationBean.addInitParameter("resetEnable","false");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean statFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        //添加过滤规则.
        filterRegistrationBean.addUrlPatterns("/*");
        //添加不需要忽略的格式信息.
        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
        }
}

  1.4 配置数据源的信息

  告诉springboot采用Druid数据源:

 @Bean(name = "dataSource")
     @Primary
     @ConfigurationProperties(prefix = "spring.datasource")
     public DataSource dataSource(){
         return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
     }

  接下来就可以通过localhost:8080/druid/index.html去打开控制台,观察过滤信息了!



二.使用@Cache简化redis配置

  在实体类比较简单的时候(例如:没有一对多,多对多这类复杂的关系,不是List,Map这类数据类型,只是一个Pojo类),可以使用@Cache去替代书写BeanRedis注入RedisTemplate的方式去访问Redis数据库.

  2.1 建立RoleService.采用@Cacheable和@CachePut去访问Redis

  实体类的主要属性如下:

2.1 建立Redis配置类,需要去配置Redis的注解

@ConfigurationProperties("application.properties")
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

     @Value("${spring.redis.hostName}")
        private String hostName;
        @Value("${spring.redis.port}")
        private Integer port;

        @Bean
        public RedisConnectionFactory redisConnectionFactory() {
            JedisConnectionFactory cf = new JedisConnectionFactory();
            cf.setHostName(hostName);
            cf.setPort(port);
            cf.afterPropertiesSet();
            return cf;
        }
    //配置key的生成
    @Bean
    public KeyGenerator simpleKey(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName()+":");
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
  //配置key的生成
    @Bean
    public KeyGenerator objectId(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params){
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName()+":");
                try {
                    sb.append(params[0].getClass().getMethod("getId", null).invoke(params[0], null).toString());
                }catch (NoSuchMethodException no){
                    no.printStackTrace();
                }catch(IllegalAccessException il){
                    il.printStackTrace();
                }catch(InvocationTargetException iv){
                    iv.printStackTrace();
                }
                return sb.toString();
            }
        };
    }
    //配置注解
    @Bean
    public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        RedisCacheManager manager = new RedisCacheManager(redisTemplate);
        manager.setDefaultExpiration(43200);//12小时
        return manager;
    }
    //对于复杂的属性仍然使用RedisTemplate
    @Bean
    public RedisTemplate<String, String> redisTemplate(
            RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(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.afterPropertiesSet();
        return template;
    }

}

2.2
  • 编写redis的service类操作edis数据库

package cn.springboot.mybatis.service;

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

@Service
public class RedisService {
@Autowired
private RedisTemplate redisTemplate;
/**
* 写入缓存
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存设置时效时间
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 批量删除对应的value
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}

/**
* 批量删除key
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* 删除对应的value
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 哈希 添加
* @param key
* @param hashKey
* @param value
*/
public void hmSet(String key, Object hashKey, Object value){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key,hashKey,value);
}

/**
* 哈希获取数据
* @param key
* @param hashKey
* @return
*/
public Object hmGet(String key, Object hashKey){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key,hashKey);
}

/**
* 列表添加
* @param k
* @param v
*/
public void lPush(String k,Object v){
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k,v);
}

/**
* 列表获取
* @param k
* @param l
* @param l1
* @return
*/
public List<Object> lRange(String k, long l, long l1){
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k,l,l1);
}

/**
* 集合添加
* @param key
* @param value
*/
public void add(String key,Object value){
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key,value);
}

/**
* 集合获取
* @param key
* @return
*/
public Set<Object> setMembers(String key){
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}

/**
* 有序集合添加
* @param key
* @param value
* @param scoure
*/
public void zAdd(String key,Object value,double scoure){
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key,value,scoure);
}

/**
* 有序集合获取
* @param key
* @param scoure
* @param scoure1
* @return
*/
public Set<Object> rangeByScore(String key,double scoure,double scoure1){
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, scoure, scoure1);
}
}

2.3 controller测试

@RestController
public class MessageController {
@Autowired
private RedisService redisService;
/* @RequestMapping(value = "/message",method = RequestMethod.GET)
@ResponseBody
public List<String> greeting(String user) {
List<String> messages = cacheService.listMessages(user);
return messages;
}*/
@RequestMapping(value = "/message1",method = RequestMethod.GET)
@ResponseBody
public String saveGreeting(String user,String message) {
String usestrr="hello";
String message1="world";
redisService.set("002", message1);
return "OK";
}
}

补充:

使用@Cache简化redis配置

  在实体类比较简单的时候(例如:没有一对多,多对多这类复杂的关系,不是List,Map这类数据类型,只是一个Pojo类),可以使用@Cache去替代书写BeanRedis注入RedisTemplate的方式去访问Redis数据库.

  2.1 建立RoleService.采用@Cacheable和@CachePut去访问Redis

  实体类的主要属性如下:

本例子没用使用该方法赶兴趣的可以试一下下面是源码

@Service
public class RoleService {
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private RoleRedis roleRedis;

    @Cacheable(value = "mysql:findById:role", keyGenerator = "simpleKey")
    public Role findById(Long id) {
        System.out.println("从数据库中查询");
        return roleRepository.findOne(id);
    }

    @CachePut(value = "mysql:findById:role", keyGenerator = "objectId")
    public Role create(Role role) {
        System.out.println("************在数据库中创建************");
        return roleRepository.save(role);
    }
    //简单的操作使用注解的形式
    @CachePut(value = "mysql:findById:role", keyGenerator = "objectId")
    public Role update(Role role) {
        System.out.println("************在数据库中更新************");
        return roleRepository.save(role);
    }

    @CacheEvict(value = "mysql:findById:role", keyGenerator = "simpleKey")
    public void delete(Long id) {
        System.out.println("************在数据库中销毁************");
        roleRepository.delete(id);
    }

    public List<Role> findAll(){
        List<Role> roleList = roleRedis.getList("mysql:findAll:role");
        if(roleList == null) {
            roleList = roleRepository.findAll();
            if(roleList != null)
                roleRedis.add("mysql:findAll:role", 5L, roleList);
        }
        return roleList;
    }
    //复杂的依然使用RedisTemplate的形式
    public Page<Role> findPage(RoleQo roleQo){
       Pageable pageable = new PageRequest(roleQo.getPage(), roleQo.getSize(), new Sort(Sort.Direction.ASC, "id"));

        PredicateBuilder pb  = new PredicateBuilder();

        if (!StringUtils.isEmpty(roleQo.getName())) {
            pb.add("name","%" + roleQo.getName() + "%", LinkEnum.LIKE);
        }

        Page<Role> pages = roleRepository.findAll(pb.build(), Operator.AND, pageable);
        return pages;
    }

}

本文章参考一下两篇博客

1

http://www.cnblogs.com/hlhdidi/p/6350306.html

2

http://www.cnblogs.com/haitao-xie/p/6323423.html


时间: 2024-11-07 13:36:33

springboot整合redis的相关文章

九、springboot整合redis二之缓冲配置

1.创建Cache配置类 @Configuration @EnableCaching public class RedisCacheConfig extends CachingConfigurerSupport { @Value("${redis.cache.expiration}") private Long expiration; /** * * 管理缓存 */ @Bean public CacheManager cacheManager(RedisTemplate<Obje

SpringBoot 整合 Redis缓存

在我们的日常项目开发过程中缓存是无处不在的,因为它可以极大的提高系统的访问速度,关于缓存的框架也种类繁多,今天主要介绍的是使用现在非常流行的NoSQL数据库(Redis)来实现我们的缓存需求. SpringBoot整合Redis是非常方便快捷的,我用的是Mybatis,这里就不说Springboot整合Mybatis了网上有很多,同样非常简单. 下面进入正题: 原文地址:https://www.cnblogs.com/yueguanguanyun/p/9756058.html

三:Springboot整合Redis

一:springboot整合redis redis版本:3.0.0 运行环境:linux 1.安装redis 1.1安装gcc yum install gcc-c++ 1.2解压redis.3.0.0.tar.gz压缩包 tar -zxvf redis-3.0.0.tar.gz 1.3进入解压后的目录进行编译 cd redis-3.0.0 make 1.4将redis安装到指定目录 make PREFIX=/usr/local/redis install 1.5启动redis ./redis-s

SpringBoot整合Redis并完成工具类

SpringBoot整合Redis的资料很多,但是我只需要整合完成后,可以操作Redis就可以了,所以不需要配合缓存相关的注解使用(如@Cacheable),而且我的系统框架用的日志是log4j,不是SpringBoot默认的Logback.通过查询资料我完成了Redis整合,并写了Redis操作工具类.特意在此记录一下,分享给大家,也方便以后查阅. 1.SpringBoot版本如下 <parent> <groupId>org.springframework.boot</gr

超简单!!!SpringBoot整合Redis

1.导入Pom.xml依赖 1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.ap

Spring Boot 学习----SpringBoot整合Redis

SpringBoot整合Redis 说明:由于使用的是window系统,所以本文中使用的redis是再Docker中运行的. 至于如何启动redis这里不再说明,需要的请自行百度. 配置pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </depend

八、springboot整合redis

整合Redis 一. 注解方式实现添加缓存 1.在pom.xml加入依赖 <!-- 配置使用redis启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency> 2. 修改引导类 修改开启缓存,添加注解@EnableCachi

SpringBoot整合Redis初实践

Redis是一个开源(BSD许可),内存存储的数据结构服务器,可用作数据库,高速缓存和消息队列代理. 有时,为了提升整个网站的性能,在开发时会将经常访问的数据进行缓存,这样在调用这个数据接口时,可以提高数据加载的效率 本文将在Boot项目中进行Redis的整合,将常用的数据缓存到Redis服务器中,提高常用服务的并发能力. 项目环境: jdk1.8 maven3.5 spring boot 2.0.4.RELEASE spring-boot-starter-data-redis 2.0.4.RE

SpringBoot整合Redis注意的一些问题

1:ERR value is not an integer or out of range 1-1:背景 使用redisTemplate.opsForValue().increment(key, delat)方法. 1-2:分析 分析:redis对任何不合法的值,都称为ERR.只有使用StringRedisSerializer序列化器才能使用incrment或者decrement方法 1-3:问题解决 使用GenericToStringSerializer.StringRedisSerializ