Springboot实现对Redis的增删改查

1.Maven加载需要的包

          <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.33</version>
        </dependency>
        <!--热部署的jar包 ,对redis序列化有影响-->
        <!--<dependency>-->
            <!--<groupId>org.springframework.boot</groupId>-->
            <!--<artifactId>spring-boot-devtools</artifactId>-->
        <!--</dependency>-->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>
        <!--jpa的jar包 ,操作数据库的-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
        </dependency>
   
  

 

2.Redis配置

package com.hpm.blog.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.lang.reflect.Method;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{

    @Bean
    public KeyGenerator wiselyKeyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

    @Bean
    public CacheManager cacheManager(
            @SuppressWarnings("rawtypes") RedisConnectionFactory connectionFactory) {
        RedisCacheManager rm = RedisCacheManager.create(connectionFactory);
        return rm;
    }

    @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;
    }
}

 

3.application.yml,连接运行Redis配置

redis:
    #Redis数据库索引
    database: 0
    #Redis服务器地址
    host: 127.0.0.1
    #Redis服务器端口
    port: 6379
    #Redis密码
    password: 123456
    #自动重连时间
    timeout: 0ms
    #
    jedis:
      pool:
        #连接池最大连接数(使用负值表示没有限制)
        max-active: 8
        #连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1ms
        #连接池中的最大空闲连接
        max-idle: 8
        #连接池中的最小空闲连接
        min-idle: 0

 

4.实例化对象

package com.hpm.blog.model;

import java.io.Serializable;

public class RedisUser implements Serializable {
    public RedisUser() {
    }

    private Integer id;
    private String name;
    private String age;
    public RedisUser(int id, String name, String age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }

}

 

5.实现redis操作

package com.hpm.blog.service;

import java.io.StringReader;
import java.security.PublicKey;
import java.util.Date;
import java.util.concurrent.TimeUnit;


import com.hpm.blog.model.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.hpm.blog.model.RedisUser;

import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import com.hpm.blog.service.UserService;

@Service
public class RedisUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    //查询缓存数据
    @Cacheable(value = "users",key = "#name")
    public RedisUser findUser(String name) {

        RedisUser redisUser = new RedisUser();

        return redisUser;
    }
    //删除缓存数据
    @CacheEvict(value = "users", key = "#name")
    public int removeUser(String name) {
        return 0;
    }
    //更新或者是增加数据
    @CachePut(value = "users",key="#redisUser.getName()" )
    public RedisUser saveUser(RedisUser redisUser) {

        return redisUser;
    }

}

 

6.控制层调用redis操作接口

package com.hpm.blog.api;

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.RestController;

import com.hpm.blog.service.RedisUserService;
import com.hpm.blog.model.RedisUser;

@RestController
public class RedisUserApi {

    @Autowired
    RedisUserService redisUserService;
    //查找redis中数据
    @GetMapping("/api/Redis/findRedisUser")
    public RedisUser finduser() {
        return redisUserService.findUser("lisi");
    }
    //增加及修改redis数据
    @GetMapping("/api/Redis/addRedisUser")
    public RedisUser adduser() {
        RedisUser redisUser = new RedisUser();
        redisUser.setName("lisi1");
        redisUser.setAge("100");
        redisUser.setId(2);
        return redisUserService.saveUser(redisUser);
    }
    //删除redis数据
    @GetMapping("/api/Redis/deleteRedisUser")
    public void removeUser() {
        redisUserService.removeUser("lisi1");
    }
}

 

7.测试

  • Redis索引为0的数据库数据状态

  • 新增

  • 查询

  • 删除


版权声明:本文为sunhuansheng原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。