搜尋
首頁資料庫RedisSpringBoot整合Redis如何使用RedisRepositories

    SpringBoot整合Redis

     1.新增redis依賴

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-pool2</artifactId>
    </dependency>

    2.在application.properties中新增redis設定資訊

    spring.redis.host=127.0.0.1
    # Redis服务器连接端口
    spring.redis.port=6379
    # Redis服务器连接密码(默认为空)
    spring.redis.password=
    # 连接池最大连接数(使用负值表示没有限制)
    spring.redis.lettuce.pool.max-active=8
    # 连接池最大阻塞等待时间(使用负值表示没有限制)
    spring.redis.lettuce.pool.max-wait=-1
    # 连接池中的最大空闲连接
    spring.redis.lettuce.pool.max-idle=8
    # 连接池中的最小空闲连接
    spring.redis.lettuce.pool.min-idle=0
    # 连接超时时间(毫秒)
    spring.redis.timeout=30000

    3.SpringBoot啟動類別中新增註解配置

    @EnableCaching
    @EnableRedisRepositories
    //注解开启使用RedisRepositories
    //CRUD操作将会操作redis中的数据
    @SpringBootApplication
    public class RedisApplication {
     
        public static void main(String[] args) {
            SpringApplication.run(RedisApplication.class, args);
        } 
    }

    4.建立實體類別Entity

    @Data
    @RedisHash("user")
    //RedisHash非常重要
    //user表示在redis中新建user集合
    //之后所有的UserEntity的保存操作全部会保存在user这个集合中
    //保存时Key的格式为——user:id
    public class UserEntity{
        @Id
        private Long id; 
        private String name; 
        private Integer age; 
        private Date createTime = new Date();
    }

    5.建立Dao層——資料操作層

    @Repository
    public interface UserDao extends CrudRepository<UserEntity,Long> {
    }

    6.建立Service層——服務層

    @Service
    public class UserService {
     
        @Autowired
        private UserDao userDao;
     
    //因为使用了RedisRepositories,所以简单的crud将不用使用RedisTemplate
    //    @Autowired
    //    private RedisTemplate redisTemplate; 
     
        /**
         * 按user:id的方式存入redis
         * @param user
         */
        public void save(UserEntity user){
            //redisTemplate.opsForValue().set(new Random().nextDouble() + "",user); 
            userDao.save(user); 
        }
     
        /**
         * 根据key从redis中查找对应value
         * @param id
         * @return
         */
        public UserEntity findOne(Long id){ 
            //UserEntity user = (UserEntity) redisTemplate.opsForValue().get(key); 
            UserEntity user = userDao.findById(id).get(); 
            return user;
        }
    }

    7.建立Controller層——控制層

    @RestController
    @RequestMapping("user")
    public class UserController {
     
        @Autowired
        private UserService userService;
     
        /**
         * 保存到redis中
         * @return
         */
        @GetMapping("save")
        public String save(){
     
            UserEntity user = new UserEntity(); 
            user.setName(String.valueOf(new Random().nextInt(100000))); 
            user.setAge(new Random().nextInt(100000)); 
            userService.save(user); 
            System.out.println(user.toString()); 
            return "success";
        }
     
        /**
         * 根据key从redis中查找value
         * @param id
         * @return
         */
        @GetMapping("find/{id}")
        public String find(@PathVariable Long id){
           UserEntity user = userService.findOne(id);
     
            System.out.println(user);
            return "success";
        }
    }

    8.redis設定類別

    @Configuration
    public class RedisConfig {
     
        @Bean
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
            RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
            template.setConnectionFactory(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);
            StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
            // key采用String的序列化方式
            template.setKeySerializer(stringRedisSerializer);
            // hash的key也采用String的序列化方式
            template.setHashKeySerializer(stringRedisSerializer);
            // value序列化方式采用jackson
            template.setValueSerializer(jackson2JsonRedisSerializer);
            // hash的value序列化方式采用jackson
            template.setHashValueSerializer(jackson2JsonRedisSerializer);
            template.afterPropertiesSet();
            return template;
        }
    }

    Redis中的結構為

    SpringBoot整合Redis如何使用RedisRepositories

    redis封裝工具類別

    @Component
    public class RedisUtils {
     
    	@Autowired
    	private RedisTemplate<String, Object> redisTemplate;
     
    	// =============================common============================
     
    	/**
    	 * 指定缓存失效时间
    	 *
    	 * @param key  键
    	 * @param time 时间(秒)
    	 * @return
    	 */
    	public boolean expire(String key, long time) {
    		try {
    			if (time > 0) {
    				redisTemplate.expire(key, time, TimeUnit.SECONDS);
    			}
    			return true;
    		} catch (Exception e) {
    			e.printStackTrace();
    			return false;
    		}
    	}
     
    	/**
    	 * 根据key 获取过期时间
    	 *
    	 * @param key 键 不能为null
    	 * @return 时间(秒) 返回0代表为永久有效
    	 */
    	public long getExpire(String key) {
    		return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    	}
     
    	/**
    	 * 判断key是否存在
    	 *
    	 * @param key 键
    	 * @return true 存在 false不存在
    	 */
    	public boolean hasKey(String key) {
    		try {
    			return redisTemplate.hasKey(key);
    		} catch (Exception e) {
    			e.printStackTrace();
    			return false;
    		}
    	}
     
    	/**
    	 * 删除缓存
    	 *
    	 * @param key 可以传一个值 或多个
    	 */
    	@SuppressWarnings("unchecked")
    	public void del(String... key) {
    		if (key != null && key.length > 0) {
    			if (key.length == 1) {
    				redisTemplate.delete(key[0]);
    			} else {
    				redisTemplate.delete(CollectionUtils.arrayToList(key));
    			}
    		}
    	}
    	// ============================String=============================
     
    	/**
    	 * 普通缓存获取
    	 *
    	 * @param key 键
    	 * @return 值
    	 */
    	public  Object get(String key) {
    		return key == null ? null : redisTemplate.opsForValue().get(key);
    	}
     
    	/**
    	 * 普通缓存放入
    	 *
    	 * @param key   键
    	 * @param value 值
    	 * @return true成功 false失败
    	 */
    	public boolean set(String key, Object value) {
    		try {
    			redisTemplate.opsForValue().set(key, value);
    			return true;
    		} catch (Exception e) {
    			e.printStackTrace();
    			return false;
    		}
    	}
     
    	/**
    	 * 普通缓存放入并设置时间
    	 *
    	 * @param key   键
    	 * @param value 值
    	 * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
    	 * @return true成功 false 失败
    	 */
    	public boolean set(String key, Object value, long time) {
    		try {
    			if (time > 0) {
    				redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    			} else {
    				set(key, value);
    			}
    			return true;
    		} catch (Exception e) {
    			e.printStackTrace();
    			return false;
    		}
    	}
     
    	/**
    	 * 递增
    	 *
    	 * @param key   键
    	 * @param delta 要增加几(大于0)
    	 * @return
    	 */
    	public long incr(String key, long delta) {
    		if (delta < 0) {
    			throw new RuntimeException("递增因子必须大于0");
    		}
    		return redisTemplate.opsForValue().increment(key, delta);
    	}
     
    	/**
    	 * 递减
    	 *
    	 * @param key   键
    	 * @param delta 要减少几(小于0)
    	 * @return
    	 */
    	public long decr(String key, long delta) {
    		if (delta < 0) {
    			throw new RuntimeException("递减因子必须大于0");
    		}
    		return redisTemplate.opsForValue().increment(key, -delta);
    	}
    	// ================================Map=================================
     
    	/**
    	 * HashGet
    	 *
    	 * @param key  键 不能为null
    	 * @param item 项 不能为null
    	 * @return 值
    	 */
    	public Object hget(String key, String item) {
    		return redisTemplate.opsForHash().get(key, item);
    	}
     
    	/**
    	 * 获取hashKey对应的所有键值
    	 *
    	 * @param key 键
    	 * @return 对应的多个键值
    	 */
    	public Map<Object, Object> hmget(String key) {
    		return redisTemplate.opsForHash().entries(key);
    	}
     
    	/**
    	 * HashSet
    	 *
    	 * @param key 键
    	 * @param map 对应多个键值
    	 * @return true 成功 false 失败
    	 */
    	public boolean hmset(String key, Map<String, Object> map) {
    		try {
    			redisTemplate.opsForHash().putAll(key, map);
    			return true;
    		} catch (Exception e) {
    			e.printStackTrace();
    			return false;
    		}
    	}
     
    	/**
    	 * HashSet 并设置时间
    	 *
    	 * @param key  键
    	 * @param map  对应多个键值
    	 * @param time 时间(秒)
    	 * @return true成功 false失败
    	 */
    	public boolean hmset(String key, Map<String, Object> map, long time) {
    		try {
    			redisTemplate.opsForHash().putAll(key, map);
    			if (time > 0) {
    				expire(key, time);
    			}
    			return true;
    		} catch (Exception e) {
    			e.printStackTrace();
    			return false;
    		}
    	}
     
    	/**
    	 * 向一张hash表中放入数据,如果不存在将创建
    	 *
    	 * @param key   键
    	 * @param item  项
    	 * @param value 值
    	 * @return true 成功 false失败
    	 */
    	public boolean hset(String key, String item, Object value) {
    		try {
    			redisTemplate.opsForHash().put(key, item, value);
    			return true;
    		} catch (Exception e) {
    			e.printStackTrace();
    			return false;
    		}
    	}
     
    	/**
    	 * 向一张hash表中放入数据,如果不存在将创建
    	 *
    	 * @param key   键
    	 * @param item  项
    	 * @param value 值
    	 * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
    	 * @return true 成功 false失败
    	 */
    	public boolean hset(String key, String item, Object value, long time) {
    		try {
    			redisTemplate.opsForHash().put(key, item, value);
    			if (time > 0) {
    				expire(key, time);
    			}
    			return true;
    		} catch (Exception e) {
    			e.printStackTrace();
    			return false;
    		}
    	}
     
    	/**
    	 * 删除hash表中的值
    	 *
    	 * @param key  键 不能为null
    	 * @param item 项 可以使多个 不能为null
    	 */
    	public void hdel(String key, Object... item) {
    		redisTemplate.opsForHash().delete(key, item);
    	}
     
    	/**
    	 * 判断hash表中是否有该项的值
    	 *
    	 * @param key  键 不能为null
    	 * @param item 项 不能为null
    	 * @return true 存在 false不存在
    	 */
    	public boolean hHasKey(String key, String item) {
    		return redisTemplate.opsForHash().hasKey(key, item);
    	}
     
    	/**
    	 * hash递增 如果不存在,就会创建一个 并把新增后的值返回
    	 *
    	 * @param key  键
    	 * @param item 项
    	 * @param by   要增加几(大于0)
    	 * @return
    	 */
    	public double hincr(String key, String item, double by) {
    		return redisTemplate.opsForHash().increment(key, item, by);
    	}
     
    	/**
    	 * hash递减
    	 *
    	 * @param key  键
    	 * @param item 项
    	 * @param by   要减少记(小于0)
    	 * @return
    	 */
    	public double hdecr(String key, String item, double by) {
    		return redisTemplate.opsForHash().increment(key, item, -by);
    	}
    	// ============================set=============================
     
    	/**
    	 * 根据key获取Set中的所有值
    	 *
    	 * @param key 键
    	 * @return
    	 */
    	public Set<Object> sGet(String key) {
    		try {
    			return redisTemplate.opsForSet().members(key);
    		} catch (Exception e) {
    			e.printStackTrace();
    			return null;
    		}
    	}
     
    	/**
    	 * 根据value从一个set中查询,是否存在
    	 *
    	 * @param key   键
    	 * @param value 值
    	 * @return true 存在 false不存在
    	 */
    	public boolean sHasKey(String key, Object value) {
    		try {
    			return redisTemplate.opsForSet().isMember(key, value);
    		} catch (Exception e) {
    			e.printStackTrace();
    			return false;
    		}
    	}
     
    	/**
    	 * 将数据放入set缓存
    	 *
    	 * @param key    键
    	 * @param values 值 可以是多个
    	 * @return 成功个数
    	 */
    	public long sSet(String key, Object... values) {
    		try {
    			return redisTemplate.opsForSet().add(key, values);
    		} catch (Exception e) {
    			e.printStackTrace();
    			return 0;
    		}
    	}
     
    	/**
    	 * 将set数据放入缓存
    	 *
    	 * @param key    键
    	 * @param time   时间(秒)
    	 * @param values 值 可以是多个
    	 * @return 成功个数
    	 */
    	public long sSetAndTime(String key, long time, Object... values) {
    		try {
    			Long count = redisTemplate.opsForSet().add(key, values);
    			if (time > 0)
    				expire(key, time);
    			return count;
    		} catch (Exception e) {
    			e.printStackTrace();
    			return 0;
    		}
    	}
     
    	/**
    	 * 获取set缓存的长度
    	 *
    	 * @param key 键
    	 * @return
    	 */
    	public long sGetSetSize(String key) {
    		try {
    			return redisTemplate.opsForSet().size(key);
    		} catch (Exception e) {
    			e.printStackTrace();
    			return 0;
    		}
    	}
     
    	/**
    	 * 移除值为value的
    	 *
    	 * @param key    键
    	 * @param values 值 可以是多个
    	 * @return 移除的个数
    	 */
    	public long setRemove(String key, Object... values) {
    		try {
    			Long count = redisTemplate.opsForSet().remove(key, values);
    			return count;
    		} catch (Exception e) {
    			e.printStackTrace();
    			return 0;
    		}
    	}
    	// ===============================list=================================
     
    	/**
    	 * 获取list缓存的内容
    	 *
    	 * @param key   键
    	 * @param start 开始
    	 * @param end   结束 0 到 -1代表所有值
    	 * @return
    	 */
    	public List<Object> lGet(String key, long start, long end) {
    		try {
    			return redisTemplate.opsForList().range(key, start, end);
    		} catch (Exception e) {
    			e.printStackTrace();
    			return null;
    		}
    	}
     
    	/**
    	 * 获取list缓存的长度
    	 *
    	 * @param key 键
    	 * @return
    	 */
    	public long lGetListSize(String key) {
    		try {
    			return redisTemplate.opsForList().size(key);
    		} catch (Exception e) {
    			e.printStackTrace();
    			return 0;
    		}
    	}
     
    	/**
    	 * 通过索引 获取list中的值
    	 *
    	 * @param key   键
    	 * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
    	 * @return
    	 */
    	public Object lGetIndex(String key, long index) {
    		try {
    			return redisTemplate.opsForList().index(key, index);
    		} catch (Exception e) {
    			e.printStackTrace();
    			return null;
    		}
    	}
     
    	/**
    	 * 将list放入缓存
    	 *
    	 * @param key   键
    	 * @param value 值
    	 * @return
    	 */
    	public boolean lSet(String key, Object value) {
    		try {
    			redisTemplate.opsForList().rightPush(key, value);
    			return true;
    		} catch (Exception e) {
    			e.printStackTrace();
    			return false;
    		}
    	}
     
    	/**
    	 * 将list放入缓存
    	 *
    	 * @param key   键
    	 * @param value 值
    	 * @param time  时间(秒)
    	 * @return
    	 */
    	public boolean lSet(String key, Object value, long time) {
    		try {
    			redisTemplate.opsForList().rightPush(key, value);
    			if (time > 0)
    				expire(key, time);
    			return true;
    		} catch (Exception e) {
    			e.printStackTrace();
    			return false;
    		}
    	}
     
    	/**
    	 * 将list放入缓存
    	 *
    	 * @param key   键
    	 * @param value 值
    	 * @return
    	 */
    	public boolean lSet(String key, List<Object> value) {
    		try {
    			redisTemplate.opsForList().rightPushAll(key, value);
    			return true;
    		} catch (Exception e) {
    			e.printStackTrace();
    			return false;
    		}
    	}
     
    	/**
    	 * 将list放入缓存
    	 *
    	 * @param key   键
    	 * @param value 值
    	 * @param time  时间(秒)
    	 * @return
    	 */
    	public boolean lSet(String key, List<Object> value, long time) {
    		try {
    			redisTemplate.opsForList().rightPushAll(key, value);
    			if (time > 0)
    				expire(key, time);
    			return true;
    		} catch (Exception e) {
    			e.printStackTrace();
    			return false;
    		}
    	}
     
    	/**
    	 * 根据索引修改list中的某条数据
    	 *
    	 * @param key   键
    	 * @param index 索引
    	 * @param value 值
    	 * @return
    	 */
    	public boolean lUpdateIndex(String key, long index, Object value) {
    		try {
    			redisTemplate.opsForList().set(key, index, value);
    			return true;
    		} catch (Exception e) {
    			e.printStackTrace();
    			return false;
    		}
    	}
     
    	/**
    	 * 移除N个值为value
    	 *
    	 * @param key   键
    	 * @param count 移除多少个
    	 * @param value 值
    	 * @return 移除的个数
    	 */
    	public long lRemove(String key, long count, Object value) {
    		try {
    			Long remove = redisTemplate.opsForList().remove(key, count, value);
    			return remove;
    		} catch (Exception e) {
    			e.printStackTrace();
    			return 0;
    		}
    	}
    }

    以上是SpringBoot整合Redis如何使用RedisRepositories的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    陳述
    本文轉載於:亿速云。如有侵權,請聯絡admin@php.cn刪除
    REDIS:它如何充當數據存儲和服務REDIS:它如何充當數據存儲和服務Apr 24, 2025 am 12:08 AM

    REDISACTSASBOTHADATASTOREANDASERVICE.1)ASADATASTORE,ITUSESIN-MEMORYSTOOGATOFORFOFFASTESITION,支持VariousDatharptructuresLikeKey-valuepairsandsortedsetsetsetsetsetsetsets.2)asaservice,ItprovidespunctionslikeItionitionslikepunikeLikePublikePublikePlikePlikePlikeAndluikeAndluAascriptingiationsmpleplepleclexplectiations

    REDIS與其他數據庫:比較分析REDIS與其他數據庫:比較分析Apr 23, 2025 am 12:16 AM

    Redis與其他數據庫相比,具有以下獨特優勢:1)速度極快,讀寫操作通常在微秒級別;2)支持豐富的數據結構和操作;3)靈活的使用場景,如緩存、計數器和發布訂閱。選擇Redis還是其他數據庫需根據具體需求和場景,Redis在高性能、低延遲應用中表現出色。

    REDIS的角色:探索數據存儲和管理功能REDIS的角色:探索數據存儲和管理功能Apr 22, 2025 am 12:10 AM

    Redis在數據存儲和管理中扮演著關鍵角色,通過其多種數據結構和持久化機製成為現代應用的核心。 1)Redis支持字符串、列表、集合、有序集合和哈希表等數據結構,適用於緩存和復雜業務邏輯。 2)通過RDB和AOF兩種持久化方式,Redis確保數據的可靠存儲和快速恢復。

    REDIS:了解NOSQL概念REDIS:了解NOSQL概念Apr 21, 2025 am 12:04 AM

    Redis是一種NoSQL數據庫,適用於大規模數據的高效存儲和訪問。 1.Redis是開源的內存數據結構存儲系統,支持多種數據結構。 2.它提供極快的讀寫速度,適合緩存、會話管理等。 3.Redis支持持久化,通過RDB和AOF方式確保數據安全。 4.使用示例包括基本的鍵值對操作和高級的集合去重功能。 5.常見錯誤包括連接問題、數據類型不匹配和內存溢出,需注意調試。 6.性能優化建議包括選擇合適的數據結構和設置內存淘汰策略。

    REDIS:現實世界的用例和示例REDIS:現實世界的用例和示例Apr 20, 2025 am 12:06 AM

    Redis在現實世界中的應用包括:1.作為緩存系統加速數據庫查詢,2.存儲Web應用的會話數據,3.實現實時排行榜,4.作為消息隊列簡化消息傳遞。 Redis的多功能性和高性能使其在這些場景中大放異彩。

    REDIS:探索其功能和功能REDIS:探索其功能和功能Apr 19, 2025 am 12:04 AM

    Redis脫穎而出是因為其高速、多功能性和豐富的數據結構。 1)Redis支持字符串、列表、集合、散列和有序集合等數據結構。 2)它通過內存存儲數據,支持RDB和AOF持久化。 3)從Redis6.0開始引入多線程處理I/O操作,提升了高並發場景下的性能。

    Redis是SQL還是NOSQL數據庫?答案解釋了Redis是SQL還是NOSQL數據庫?答案解釋了Apr 18, 2025 am 12:11 AM

    RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

    REDIS:提高應用程序性能和可擴展性REDIS:提高應用程序性能和可擴展性Apr 17, 2025 am 12:16 AM

    Redis通過緩存數據、實現分佈式鎖和數據持久化來提升應用性能和可擴展性。 1)緩存數據:使用Redis緩存頻繁訪問的數據,提高數據訪問速度。 2)分佈式鎖:利用Redis實現分佈式鎖,確保在分佈式環境中操作的安全性。 3)數據持久化:通過RDB和AOF機制保證數據安全性,防止數據丟失。

    See all articles

    熱AI工具

    Undresser.AI Undress

    Undresser.AI Undress

    人工智慧驅動的應用程序,用於創建逼真的裸體照片

    AI Clothes Remover

    AI Clothes Remover

    用於從照片中去除衣服的線上人工智慧工具。

    Undress AI Tool

    Undress AI Tool

    免費脫衣圖片

    Clothoff.io

    Clothoff.io

    AI脫衣器

    Video Face Swap

    Video Face Swap

    使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

    熱工具

    SublimeText3漢化版

    SublimeText3漢化版

    中文版,非常好用

    SublimeText3 英文版

    SublimeText3 英文版

    推薦:為Win版本,支援程式碼提示!

    SublimeText3 Linux新版

    SublimeText3 Linux新版

    SublimeText3 Linux最新版

    WebStorm Mac版

    WebStorm Mac版

    好用的JavaScript開發工具

    mPDF

    mPDF

    mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),